Last active
January 7, 2020 07:50
-
-
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
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
| 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