forked from vishal8113/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchinRotatedarray.java
53 lines (50 loc) · 1.56 KB
/
searchinRotatedarray.java
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
class Main {
static int pivotedBinarySearch(int arr[], int n,
int key)
{
int pivot = findPivot(arr, 0, n - 1);
if (pivot == -1)
return binarySearch(arr, 0, n - 1, key);
if (arr[pivot] == key)
return pivot;
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
static int findPivot(int arr[], int low, int high)
{
if (high < low)
return -1;
if (high == low)
return low;
int mid = (low + high) / 2;
if (mid < high && arr[mid] > arr[mid + 1])
return mid;
if (mid > low && arr[mid] < arr[mid - 1])
return (mid - 1);
if (arr[low] >= arr[mid])
return findPivot(arr, low, mid - 1);
return findPivot(arr, mid + 1, high);
}
static int binarySearch(int arr[], int low, int high,
int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
public static void main(String args[])
{
int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };
int n = arr1.length;
int key = 3;
System.out.println(
"Index of the element is : "
+ pivotedBinarySearch(arr1, n, key));
}
}