Binary search is a logarithmic algorithm and executes in O(log2n) time.
Specifically, 1 + log2N iterations are needed to return an answer. In most cases it is considerably faster than a linear search. It can be implemented using recursion or iteration, as shown below. In some languages it is more elegantly expressed recursively; however, in some C-based languages tail recursion is not eliminated and the recursive version requires more stack space. http://en.wikipedia.org/wiki/Binary_search_algorithm
package com.search.binary;
import java.util.Arrays;
import com.sort.quick.QuickSort;
public class BinarySearch {
public int search(int[] data, int target) {
int index = -1;
int bottom = 0;
int top = data.length - 1;
while (bottom <= top) {
int middle = (top + bottom) / 2;
if (target < data[middle]) {
top = middle - 1;
} else if (data[middle] == target) {
return middle;
} else {
bottom = middle + 1;
}
}
return index;
}
public static void main(String[] args) {
int[] data = new int[] { 4, 8, 15, 16, 23, 42 };
System.out.println(new BinarySearch().search(data, 16));
}
}