Skip to content

Instantly share code, notes, and snippets.

@soltrinox
Created December 18, 2014 15:51
Show Gist options
  • Save soltrinox/d616f3450e26d4f734c4 to your computer and use it in GitHub Desktop.
Save soltrinox/d616f3450e26d4f734c4 to your computer and use it in GitHub Desktop.
binary search
public static int binarySearch(int[]array,int key){ //looks for the index of the element that has value key, returns index. array must be sorted
int min=0; //initializes min, max, guess
int max=array.length-1;
int guess=(min+max)/2;
while(array[guess]!=key){ //keeps on looking until key is found
if(min==guess||max==guess){//if min=guess, max=guess, the key does not exist in the array
return(-1);//returns -1 if key is not found
}
if(array[guess]>key){//you only have to search between min and guess
max=guess;
}
else{//search between max and guess
min=guess;
}
guess=(min+max)/2;//new value for guess-middle of the interval
}
return(guess);//exists the loop of key is found-returns the index
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment