1. What is Binary Search
- Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
- A simple approach is to do Linear search.
- The time complexity of above algorithm is O(n). Another approach to perform the same task is using Binary Search.
- Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
- Begin with an interval covering the whole array.
- If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
- Otherwise narrow it to the upper half.
- Repeatedly check until the value is found or the interval is empty.
The time complexity of above algorithm is O(log n).
public class BinarySearch {
public static void main(String[] args) {
int array[] = { 0};
int ele = 10;
int index = binarySearch(array, ele, 0, array.length - 1);
System.out.println("index is " + index);
}
public static int binarySearch(int array[], int ele, int min, int max) {
if (max >= min) {
int middle = (min + max) / 2;
if (ele == array[middle])
return middle;
if (ele < array[middle])
return binarySearch(array, ele, min, middle - 1);
return binarySearch(array, ele, middle + 1, max);
}
return -1;
}
}
|
No comments:
Post a Comment