-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexof an arrat.cpp
106 lines (99 loc) · 1.38 KB
/
indexof an arrat.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include<stdio.h>
#include<conio.h>
int checkoutput(int ,int);
int dotest();
int findlength(int arr[]);
int find_length(int []);
int find(int []);
int binarysearch(int ,int ,int[]);
struct test
{
int a[30];
int length;
}
testcases[4]={
{ {1,2,5,7,9,4,0,0,0,0},4},
{ {2,4,5,1,0,0},2},
{ { -1,2,5,3,0,0},2}
};
void main()
{
dotest();
getch();
}
int dotest()
{
printf("Method1:");
for( int i=0;i<3;i++)
{
int n=findlength(testcases[i].a);
checkoutput(n,testcases[i].length);
}
printf("\n Method2:");
for( int i=0;i<3;i++)
{
int n=find_length(testcases[i].a);
checkoutput(n,testcases[i].length);
}
printf("\nMethod3:");
for( int i=0;i<3;i++)
{
int n=find(testcases[i].a);
checkoutput(n,testcases[i].length);
}
return 0;
}
int checkoutput(int a, int b)
{
if(a==b)
printf("\nValid");
else
printf("\nInvalid");
return 0;
}
int findlength( int a[])
{
int i=0;
while(a[i]!=0)
{i++;
}
return i-2;
}
int find_length(int a[])
{
int i=0;
while(a[i]<a[i+1])
{
i++;
}
return i;
}
int find(int a[])
{
int j,i=1,num;
while(a[i]!=0)
{
j=i;
i=i*2;
}
int v1=j;
int v2=i;
num= binarysearch( v1,v2,a);
return num;
}
int binarysearch(int j,int i,int a[])
{
int mid;
int l=j,h=i;
while(l<=h)
{
mid=(l+h)/2;
if(a[mid]!=0 && a[mid]<a[mid-1]&& a[mid]>a[mid+1])
return mid-1;
else
if(a[mid]>a[mid-1] && a[mid]!=0)
l=l+1;
else
h=h-1;
}
}