-
Notifications
You must be signed in to change notification settings - Fork 0
/
search_sorted_rotated_array.c
90 lines (82 loc) · 1.22 KB
/
search_sorted_rotated_array.c
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<stdio.h>
#include<stdlib.h>
int findPivot(int arr[],int low,int high)
{
if(high<low)
{
return 0;
}
if(low==high)
{
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])
{
findPivot(arr,low,mid-1);
}
return findPivot(arr,mid+1,high);
}
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])
{
binarySearch(arr,mid+1,high,key);
}
return binarySearch(arr,low,mid-1,key);
}
int pivotedBinarySearch(int arr[],int n,int key)
{
int pivot=findPivot(arr,0,n-1);
if(pivot==0)
{
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,key);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
int key;
scanf("%d",&key);
//printf("Index of seached element is:\n");
int index=pivotedBinarySearch(arr,n,key);
printf("%d",index);
}
return 0;
}