Skip to content

Instantly share code, notes, and snippets.

@Jun711
Created February 16, 2018 00:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jun711/147400a27fd14a6869441fcb65cfa91e to your computer and use it in GitHub Desktop.
Save Jun711/147400a27fd14a6869441fcb65cfa91e to your computer and use it in GitHub Desktop.
TestDome - SortedSearch
public class SortedSearch {
public static int countNumbers(int[] sortedArray, int lessThan) {
if (sortedArray == null || sortedArray.length == 0)
return -1;
int totalCount = sortedArray.length;
if (sortedArray[totalCount - 1] < lessThan)
return totalCount;
int low = 0;
int high = totalCount - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (sortedArray[mid] == lessThan)
return mid;
if (sortedArray[mid] > lessThan) {
if (mid >= 1 && lessThan > sortedArray[mid - 1])
return mid;
else
high = mid - 1;
}
if (sortedArray[mid] < lessThan) {
if (mid < totalCount - 1 && lessThan <= sortedArray[mid + 1])
return mid + 1;
else
low = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(SortedSearch.countNumbers(new int[] { 1, 3, 5, 7 }, 4));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment