Binary Search

Binary Search

 

We are given a sorted array. Write a function to search an element n.

 

Binary search compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful or the remaining half is empty.

 

Running time complexity of Binary Search is O(logn).

 

 
Here is the code.
 



package com.diaryreaders.datastructures.searching;
public class BinarySearch {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8 };
int index = binarySearch(array, 6);
System.out.println(index);
}
private static int binarySearch(int[] array, int n) {
return binarySearch(array, n, 0, array.length - 1);
}
private static int binarySearch(int[] array, int n, int l, int r) {
if (r < array.length && r >= 0 && l < array.length && l >= 0) {
int mid = l + ((r - l) / 2);
if (n == array[mid]) {
return mid;
}
if (n > array[mid]) {
l = mid + 1;
return binarySearch(array, n, l, r);
} else {
r = mid - 1;
return binarySearch(array, n, l, r);
}
}
return -1;
}
}


 
Output :

 

 

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON