Monday, 15 May 2017

2. Binary Search

1. What is Binary Search
  1. Given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
  2. A simple approach is to do Linear search.
  3. The time complexity of above algorithm is O(n). Another approach to perform the same task is using Binary Search.
  4. Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
  5. Begin with an interval covering the whole array.
  6. 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.
  7. Otherwise narrow it to the upper half.
  8. 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

3. Java Program to create Binary Tree