Skip to content

Commit a89f0a7

Browse files
committed
binary search implementation without recursion
1 parent 22c0073 commit a89f0a7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Lecture14;
2+
3+
public class binarySearchNoRecursion {
4+
5+
public static void main(String[] args) {
6+
7+
int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80 };
8+
int key = 30;
9+
int result = binarySearch(arr, key);
10+
System.out.println(result); // 2
11+
System.out.println(binarySearch(arr, 70)); // 6
12+
System.out.println(binarySearch(arr, 700)); // -1
13+
}
14+
15+
public static int binarySearch(int[] arr, int key) {
16+
17+
int start = 0, end = arr.length - 1;
18+
19+
while (start <= end) {
20+
int mid = (start + end) / 2;
21+
if (arr[mid] == key) {
22+
return mid;
23+
} else if (key > arr[mid]) {
24+
start = mid + 1;
25+
} else {
26+
end = mid - 1;
27+
}
28+
}
29+
30+
return -1;
31+
}
32+
}

0 commit comments

Comments
 (0)