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

Commit b8af09c

Browse files
author
Ram swaroop
committed
binary search : modified
1 parent f62e213 commit b8af09c

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/me/ramswaroop/common/Search.java

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
public class Search {
1111

1212
/**
13-
* Searches an item in a sorted array in O(log n) time.
13+
* Searches an element {@param n} in a sorted array {@param a}
14+
* and returns its index in O(log n) time. The Index may not
15+
* correspond to the first occurrence of the element.
1416
*
1517
* @param a
1618
* @param n
@@ -21,16 +23,19 @@ public static int binarySearch(int a[], int n) {
2123
}
2224

2325
public static int binarySearch(int a[], int n, int low, int high) {
24-
int mid = (low + high) / 2;
2526

26-
if (high < low) {
27-
return -1;
28-
} else if (n == a[mid]) {
29-
return mid;
30-
} else if (n < a[mid]) {
31-
return binarySearch(a, n, 0, mid - 1);
27+
if (low <= high) {
28+
int mid = (low + high) / 2;
29+
30+
if (n == a[mid]) {
31+
return mid;
32+
} else if (n < a[mid]) {
33+
return binarySearch(a, n, 0, mid - 1);
34+
} else {
35+
return binarySearch(a, n, mid + 1, high);
36+
}
3237
} else {
33-
return binarySearch(a, n, mid + 1, high);
38+
return -1;
3439
}
3540
}
3641

@@ -41,5 +46,9 @@ public static int binarySearch(int a[], int n, int low, int high) {
4146
*/
4247
public static void main(String a[]) {
4348
System.out.println(binarySearch(new int[]{0, 2}, 2));
49+
System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 2));
50+
System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 3));
51+
System.out.println(binarySearch(new int[]{0, 2}, 0));
52+
System.out.println(binarySearch(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); // doesn't return index of first occurrence
4453
}
4554
}

0 commit comments

Comments
 (0)