-
Notifications
You must be signed in to change notification settings - Fork 93
/
BinarySearch
57 lines (48 loc) · 1.32 KB
/
BinarySearch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.ideserve.saurabh.questions;
/**
* <b>IDeserve <br>
* <a href="https://www.youtube.com/c/IDeserve">https://www.youtube.com/c/IDeserve</a>
* <br><br>
* Binary Search</b><br>
* Given a sorted integer array and an integer, find the index of the integer in the array. If not found, return -1.
*
* Example: <br>
* array = { 21, 32, 43, 74, 75, 86, 97, 108, 149 }
* <br>
* integer = 43
* <br>
* Output: 2
* <br><br>
* <a href="https://www.youtube.com/watch?v=PWFCbWt7VwY">Binary Search Youtube Link</a>
* @author Saurabh
*
*/
public class BinarySearch {
public static int findElementBinarySearch(int[] array, int num) {
if (array == null || array.length == 0) {
return -1;
}
int start = 0;
int end = array.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (array[mid] == num) {
return mid;
} else if (num < array[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int array[] = { 21, 32, 43, 74, 75, 86, 97, 108, 149 };
int num = 43;
binarySearchTest(array,num);
}
public static void binarySearchTest(int array[], int num) {
int index = findElementBinarySearch(array, num);
System.out.println("Element " + num + (index >= 0 ? (" found at index " + index) : " not found!"));
}
}