Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Last active January 7, 2020 07:50
Show Gist options
  • Select an option

  • Save drem-darios/0247bca0750ad3d96dfe0575a56fc68a to your computer and use it in GitHub Desktop.

Select an option

Save drem-darios/0247bca0750ad3d96dfe0575a56fc68a to your computer and use it in GitHub Desktop.
Counts the number of array elements that are less than the parameter lessThan
import java.util.*;
public class SortedSearch {
public static int countNumbers(int[] sortedArray, int lessThan) {
int left = 0;
int right = sortedArray.length - 1;
int count = 0;
while (left <= right)
{
int mid = (left + right) / 2;
if (sortedArray[mid] < lessThan)
{
count = mid + 1;
left = mid + 1;
}
else {
right = mid - 1;
}
}
return count;
}
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