Skip to content

Instantly share code, notes, and snippets.

@pepet96
Created March 13, 2014 01:51
Show Gist options
  • Save pepet96/9520564 to your computer and use it in GitHub Desktop.
Save pepet96/9520564 to your computer and use it in GitHub Desktop.
public static int binarySearch(int numbers[], int key) {
int mid;
int low = 0;
int high = numbers.length - 1;
while (low <= high) {
mid = (low + high) / 2;
if (numbers[mid] > key) {
high = mid - 1;
} else if (numbers[mid] < key) {
low = mid + 1;
} else {
return mid;
}
}
if(key > -1){
key = key;
return key;
}else{
if(numbers[(low + high)/2] < key){
key = (low + high/2);
}else{
for(int i = (low + high)/2; i > -1; i--){
if(numbers[i] == key){
key = i;
break;
}else if(numbers[i] < key){
key = i;
break;
}else{
key = key;
}
}
}
}
return key;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment