Created
March 13, 2014 01:51
-
-
Save pepet96/9520564 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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