-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
40 lines (36 loc) · 1.06 KB
/
BinarySearch.java
File metadata and controls
40 lines (36 loc) · 1.06 KB
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
/*
* FILENAME : BinarySearch.java
* Problem Statement: Implementation of Binary Search Class
* ------------------------------------------------------------------------------
* AUTHOR : GANESH PAI, Dept. of CS&E, NMAMIT, Nitte
* YEAR : 2021
* E-mail : ganesh.pai@nitte.edu.in
* ------------------------------------------------------------------------------
*/
public class BinarySearch
{
private final int data[], noOfElements;
public BinarySearch(int[] data, int noOfElements)
{
this.data = data;
this.noOfElements = noOfElements;
}
public int search(int elem)
{
return binsearch(0, noOfElements - 1, elem);
}
private int binsearch(int low, int high, int elem)
{
while(low <= high)
{
int mid = (low + high) / 2;
if(data[mid] == elem)
return mid + 1;
else if (data[mid] < elem)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
}