I'm trying to implement a java code to test linear search on a sorted array and this is my code
public class ArrayTest {
public static void main(String [] args) {
int []x= {12,8,6,23,6,5,17,20,9};
int y =linearSearch(x,23);
}
public static int linearSearch(int []ar,int value) {
int searchedIndex=-1;
for(int i=0;i<ar.length;i++) {
if (ar[i]==value) {
searchedIndex=i;
break;
}
}
return searchedIndex ;
}
}
The problem is that this doesn't generate any output also no errors were generated. Can anyone explain the reason for this.
Something like this:
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args) {
int[] x = {12, 8, 6, 23, 6, 5, 17, 20, 9};
// Arrays.sort(x);
int y = linearSearch(x, 23);
System.out.println("" + y);
// int z = Arrays.binarySearch(x, 23);
// System.out.println("" + z);
}
public static int linearSearch(int[] ar, int value) {
for (int i = 0; i < ar.length; i++) {
if (ar[i] == value) {
return i;
}
}
return -1;
}
}
Note the commented out lines are for if you actually wanted a sorted array instead of an unsorted array