forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bilinear_search.cpp
73 lines (61 loc) · 1.49 KB
/
bilinear_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
/*
We are given an array a[], check whether the value exists or not,
if exits print the index(1 based indexing) else print -1.
Input:
first line containes size of array.
Next line containes n space seperated intgeres.
Next line contains a value that needed to be searched.
Sample Input 1:
5
5 4 3 2 1
1
Sample Output 1:
5
Sample Input 2:
5
5 4 3 2 1
7
Sample Output 2:
-1
Bilinear approach:
Let A be the linear array of n elements. The algorithm searches for element 'key'.
Let 'index' represent the location of the element 'key' in the array.
The algorithm returns the values index=-1 if the element 'key' is not present in the array
and value index if the element 'key' is present in the array.
Language: C++17
*/
#include<bits/stdc++.h>
using namespace std;
#define MAX 100005
//bilenear search algorithm
int bilinear(vector<int>&a,int n,int key)
{
int front=0,back=n-1;
//terminating condition
while(front<=back)
{
if(a[front]==key)
return front+1;
if(a[back]==key)
return back+1;
front++;
back--;
}
return -1;
}
int main()
{
//declare and read the values of n;
int n;
cin>>n;
//declare and read the values of a[] of size n
vector<int>a(MAX);
for(int i=0;i<n;i++)
cin>>a[i];
//declare and read the value of key
int key;
cin>>key;
//Billinear approach
cout<<bilinear(a,n,key);
return 0;
}