Binary Search Java Program
Code :
class BinarySearch {
private int[] array;
int binarySearch_iterative(int low, int high, int key) {
while (low <= high){
int mid = (low+high)/2;
if(array[mid] == key) {
return mid; // serach successful
} else if(key < array[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1; // search unsuccessful
}
int binarySearch_recursive(int low, int high, int key) {
if(low <= high) {
int mid = (low+high)/2;
if(array[mid] == key) {
return mid; // serach successful
} else if(key < array[mid]) {
return binarySearch_recursive(low, mid-1, key); // search in left sub array
}
return binarySearch_recursive(mid+1, high, key); // search in right sub array
}
return -1;
}
public static void main (String[] args) {
BinarySearch obj = new BinarySearch();
obj.array = new int[] {1,2,3,4,5,6,7,8,9,10};
System.out.println(obj.binarySearch_iterative(0, 10, 6));
System.out.println(obj.binarySearch_iterative(0, 10, 60));
System.out.println(obj.binarySearch_recursive(0, 10, 6));
System.out.println(obj.binarySearch_recursive(0, 10, 60));
}
}
Comments
Post a Comment