Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5b80a89

Browse files
author
Ram swaroop
committed
smallest missing number : done
1 parent cbb4734 commit 5b80a89

File tree

1 file changed

+34
-3
lines changed

1 file changed

+34
-3
lines changed

src/me/ramswaroop/arrays/SmallestMissingNumber.java

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,42 @@
99
*/
1010
public class SmallestMissingNumber {
1111

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+
}
1443
}
1544

1645
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));
1849
}
1950
}

0 commit comments

Comments
 (0)