Skip to content

Instantly share code, notes, and snippets.

@anupsavvy
Created February 20, 2013 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anupsavvy/4998685 to your computer and use it in GitHub Desktop.
Save anupsavvy/4998685 to your computer and use it in GitHub Desktop.
Given a sorted array of integers array and an integer key, return the index of the first instance of key in the array. If key is not present in array, you should return -1. For example, given the array [-10, -2, 1, 5, 5, 8, 20] and key 5, you should return the index 3. Your solution should be a binary search, that is, it should run in O(log n) t…
public class Search{
private int binarySearch(int arr[], int key){
if(arr == null)
throw new RuntimeException("Null array found");
int l = 0; // lower limit
int h = arr.length - 1; // upper limit
int m;
while(l <= h){
m = l + (h-l)/2;
if(arr[m] == key)
return m;
else if(arr[m] > key)
h = m - 1;
else
l = m + 1;
}
return -1;
}
public static void main(String args[]){
Search search = new Search();
System.out.println("Key index is : " + search.binarySearch(new int[]{-10,-2,1,5,5,8,20},5));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment