Created
July 25, 2013 09:06
-
-
Save wuyongzheng/6078076 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 class BinarySearchAlgo | |
| { | |
| /** returns the largest index i such that array[i] ≤ needle */ | |
| public static int largestMinor (int needle, int [] array) | |
| { | |
| int low = 0, high = array.length - 1; | |
| while (low < high) { | |
| int mid = (low + high + 1) / 2; | |
| if (needle < array[mid]) | |
| high = mid - 1; | |
| else | |
| low = mid; | |
| } | |
| return low; | |
| } | |
| /** returns the smallest index i such that array[i] ≥ needle */ | |
| public static int smallestMajor (int needle, int [] array) | |
| { | |
| int low = 0, high = array.length - 1; | |
| while (low < high) { | |
| int mid = (low + high) / 2; | |
| if (needle <= array[mid]) | |
| high = mid; | |
| else | |
| low = mid + 1; | |
| } | |
| return low; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment