Binary search is faster when compared to Linear search. The pre condition for
Binary Search to work is the elements of array should be sorted.
Its time complexity is O(log n).
It works as follows,
Get the middle element of list.
If search element is less than middle element then perform Step1 by
passing first sub half (first element to middle element) as a list.
If search element is greater than middle element then perform Step1 by
passing second sub half (middle element to last element) as a list.
If search element matches with middle element then search is finished.
This example shows binary search implementation using recursive algorithm.
/**
* The precondition for binary search is the search list is sorted.
*
* @param list
* @param searchEle
* @return
*/ public static int binarySearch(int[] sortedList, int searchEle) { int index = binarySearch(sortedList, 0, sortedList.length - 1, searchEle);
System.out.println(searchEle + " found in array at index : " + index); return index;
}
public static int binarySearch(int[] sortedList, int startIndex, int endIndex, int searchEle) { if (startIndex > endIndex) { return -1;
}
int midIndex = startIndex + (endIndex - startIndex)/2;