|
9 | 9 | */
|
10 | 10 | public class SmallestMissingNumber {
|
11 | 11 |
|
12 |
| - public void smallestMissingNumber(int[] a) { |
13 |
| - |
| 12 | + /** |
| 13 | + * Modified Binary Search to find the smallest missing number in an array |
| 14 | + * {@param a} consisting of numbers between 0 to m - 1 and m > n where n is |
| 15 | + * length of array. |
| 16 | + * <p/> |
| 17 | + * EXPLANATION: |
| 18 | + * In standard Binary Search, the element to be searched is compared with |
| 19 | + * the middle element and on the basis of comparison result, we decide whether |
| 20 | + * to search is over or to go to left half or right half. |
| 21 | + * In this method, we modify the standard Binary Search algorithm to compare the |
| 22 | + * middle element with its index and make decision on the basis of this comparison. |
| 23 | + * |
| 24 | + * @param a |
| 25 | + * @param low |
| 26 | + * @param high |
| 27 | + * @return |
| 28 | + */ |
| 29 | + public static int smallestMissingNumber(int[] a, int low, int high) { |
| 30 | + if (low < high) { |
| 31 | + int mid = (low + high) / 2; |
| 32 | + |
| 33 | + if (a[mid] == mid) { |
| 34 | + return smallestMissingNumber(a, mid + 1, high); |
| 35 | + } else if (a[mid] > mid) { |
| 36 | + return smallestMissingNumber(a, low, mid - 1); |
| 37 | + } else { |
| 38 | + return smallestMissingNumber(a, mid + 1, high); |
| 39 | + } |
| 40 | + } else { |
| 41 | + return low; |
| 42 | + } |
14 | 43 | }
|
15 | 44 |
|
16 | 45 | public static void main(String a[]) {
|
17 |
| - |
| 46 | + System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 6, 9}, 0, 4)); |
| 47 | + System.out.println(smallestMissingNumber(new int[]{4, 5, 10, 11}, 0, 3)); |
| 48 | + System.out.println(smallestMissingNumber(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 10}, 0, 8)); |
18 | 49 | }
|
19 | 50 | }
|
0 commit comments