-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathsearch.java
More file actions
49 lines (42 loc) · 1.15 KB
/
search.java
File metadata and controls
49 lines (42 loc) · 1.15 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
41
42
43
44
45
46
47
48
49
class Test
{
static int binarySearch(int arr[], int l, int r, int x)
{
if (r>=l)
{
int mid = l + (r - l)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
static int findPos(int arr[],int key)
{
int l = 0, h = 1;
int val = arr[0];
// Find h to do binary search
while (val < key)
{
l = h;
if(2*h < arr.length-1)
h = 2*h;
else
h = arr.length-1;
val = arr[h]; // update new val
}
return binarySearch(arr, l, h, key);
}
public static void main(String[] args)
{
int arr[] = new int[]{3, 5, 7, 9, 10, 90,
100, 130, 140, 160, 170};
int ans = findPos(arr,10);
if (ans==-1)
System.out.println("Element not found");
else
System.out.println("Element found at index " + ans);
}
}