-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpivot.c
73 lines (61 loc) · 1.36 KB
/
pivot.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
#include<stdio.h>
#include<conio.h>
int beg,mid,end,key,p,a[10],n,result;
int pivot(int ,int,int);
int bs(int key,int beg,int end,int a[]);
void main()
{
printf("enter the no. of elements");
scanf("%d",&n);
printf("enter the elements into the array");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the element to be searched");
scanf("%d",&key);
beg=0;
end=n-1;
mid=(beg+end)/2;
p=pivot(beg,mid,end);
//now use binary search
printf("the pivot element is %d",a[p]);
beg=0;
end=n-1;
if((key>=a[beg])&&(key<=a[p-1]))
result=bs(key,beg,p-1,a);
else
result=bs(key,p,end,a);
if(result==-1)
printf("not found");
else
printf("element is found at position %d",result);
}
int pivot(int beg,int mid,int end)
{
if(a[mid]>a[mid+1])
{
return mid+1;
}
else if(a[beg]>a[mid])
{
end=mid-1;
return pivot(beg,(beg+end)/2,end);
}
else
{ beg=mid+1;
return pivot(beg,(beg+end)/2,end);
}
}
int bs(int key,int beg,int end,int a[])
{
mid=(beg+end)/2;
if(beg<end)
{
if(a[mid]==key)
return mid;
else if(a[mid]>key)
return bs(key,beg,mid-1,a);
else
return bs(key,mid+1,end,a);
}
else return -1;
}