Skip to content

Commit a65da4e

Browse files
committed
binary search implementation - O(logn)
1 parent d86a0c5 commit a65da4e

File tree

1 file changed

+35
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)