Friday, December 19, 2014
Binary Search
public class BinarySearchTest {
public static void main(String[] args){
int[] iarr = {1,3,5,7};
int key = 5;
int index = binarySearch(iarr,key);
System.out.print(key+" is at index "+index);
}
private static int binarySearch(int[] iarr, int key) {
int start = 0;
int end = iarr.length-1;
int mid = 0;
while (start<=end){
mid = (start+end)/2;
if (key==iarr[mid]) {
return mid;
}
else if (key<iarr[mid]){
end = mid -1;
}
else if (key>iarr[mid]){
start = mid+1;
}
}
return -1;
}
}
OUTPUT
5 is at index 2
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment