Skip to content

Instantly share code, notes, and snippets.

@wuyongzheng
Created July 25, 2013 09:06
Show Gist options
  • Select an option

  • Save wuyongzheng/6078076 to your computer and use it in GitHub Desktop.

Select an option

Save wuyongzheng/6078076 to your computer and use it in GitHub Desktop.
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] &ge; 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