Skip to content

Commit 5a62b0c

Browse files
committed
finds last position of search element using binary search in O(logn)
1 parent 3960e78 commit 5a62b0c

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 lastIndexSearch {
4+
5+
public static void main(String[] args) {
6+
7+
int[] arr = { 10, 20, 25, 30, 30, 30, 30, 30, 40, 50, 60, 70 };
8+
int key = 30;
9+
System.out.println(binarySearchLastIndex(arr, key));
10+
11+
}
12+
13+
public static int binarySearchLastIndex(int[] arr, int key) {
14+
15+
int start = 0, end = arr.length - 1;
16+
int ans = -1;
17+
18+
while (start <= end) {
19+
20+
int mid = (start + end) / 2;
21+
22+
if (arr[mid] == key) {
23+
ans = mid;
24+
}
25+
if (key >= arr[mid]) {
26+
start = mid + 1;
27+
} else {
28+
end = mid - 1;
29+
}
30+
}
31+
32+
return ans;
33+
}
34+
35+
}

0 commit comments

Comments
 (0)