-
Notifications
You must be signed in to change notification settings - Fork 3
/
search.cpp
138 lines (132 loc) · 2.52 KB
/
search.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include<iostream>
using namespace std;
void LinearSearch(int a[],int key,int n)
{
cout<<"IT'S LINEAR SEARCH"<<endl;
int flag=0;
int i=0;
while(i<n)
{
if(a[i]==key)
{
flag=1;
break;
}
i++;
}
if(flag)
{
cout<<"THE ELEMENT FOUND AT "<<i+1<<" POSITION"<<endl;
}
else
{
cout<<"NOT FOUND"<<endl;
}
}
void SentinelSearch(int a[],int key,int n)
{
cout<<"IT'S SENTINEL SEARCH"<<endl;
a[n]=key;
int i=0;
while(i<=n)
{
if(a[i]==key)
{
break;
}
i++;
}
if(i==n)
{
cout<<"NOT FOUND"<<endl;
}
else
{
cout<<"THE ELEMENT IS FOUND AT "<<i+1<<" POSITION"<<endl;
}
}
void BinarySearch(int a[],int key,int n)
{
cout<<"IT'S BINARY SEARCH"<<endl;
int i,j,m;
i=0;
j=n-1;
int flag=0;
while(i<=j)
{
m=(i+j)/2;
if(a[m]==key)
{
flag=1;
break;
}
if(a[m]>key)
{
j=m-1;
}
else
{
i=m+1;
}
}
if(flag)
{
cout<<"THE ELEMENT IS FOUND AT "<<m+1<<" POSITION"<<endl;
}
else
{
cout<<"NOT FOUND"<<endl;
}
}
void FibonacciSearch(int *a, int start, int end, int *fab, int index, int item)
{
int i, mid;
// Assigning middle of the array using Fibonacci element.
mid = start+fab[index-2];
// Return if item found at mid index.
if(item == a[mid])
{
cout<<"\n item found at "<<mid<<" index.";
return;
}
// Return if item found at start index.
else if(item == a[start])
{
cout<<"\n item found at "<<start<<" index.";
return;
}
// Return if item found at end index.
else if(item == a[end])
{
cout<<"\n item found at "<<end<<" index.";
return;
}
// If mid becomes start or end of the sub-array then element not found.
else if(mid == start || mid == end)
{
cout<<"\nElement not found";
return;
}
// According to the item value choose the partion to proceed further.
else if(item > a[mid])
FibonacciSearch(a, mid, end, fab, index-1, item);
else
FibonacciSearch(a, start, mid, fab, index-2, item);
}
int main()
{
int a[10],n,k;
cout<<"ENTER TOTAL NUMBER OF ELEMENTS"<<endl;
cin>>n;
cout<<"NOW ENTER THE ELEMENTS"<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"ENTER THE ELEMENT TO BE SEARCH"<<endl;
cin>>k;
LinearSearch(a,k,n);
SentinelSearch(a,k,n);
BinarySearch(a,k,n);
return 0;
}