Linear Search in Java
public class LinearSearchExample{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
Linear Search in Java (Another way)
public class LinearSearchExample {
public static int linearSearch(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
return i; // Return the index if the key is found
}
}
return -1; // Return -1 if the key is not found
}
public static void main(String[] args) {
int[] a1 = {10, 20, 30, 50, 70, 90};
int key = 50;
int resultIndex = linearSearch(a1, key);
if (resultIndex != -1) {
System.out.println(key + " is found at index: " + resultIndex);
} else {
System.out.println(key + " is not found in the array.");
}
}
}
Please give some programs on database
ReplyDelete