-
Notifications
You must be signed in to change notification settings - Fork 0
/
searching.cpp
69 lines (54 loc) · 900 Bytes
/
searching.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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int linearSearch(vector<int> arr, int x) {
int n = arr.size();
for(int i=0; i<n; i++) {
if(x == arr[i]) {
return i;
}
}
return -1;
}
int binarySearch(vector<int> arr, int x) {
//sort first
sort(arr.begin(), arr.end());
int n = arr.size();
int l = 0;
int r = n-1;
while(l <= r) {
int mid = l + (r-l)/2;
if(arr[mid] == x) {
return mid;
}
if(arr[mid] > x) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return -1;
}
int main() {
int i, n;
cout<<"Enter size of array: ";
cin>>n;
vector<int> arr;
i=0;
while(n > 0) {
cin>>i;
arr.push_back(i);
n--;
}
cout<<"Input number to be searched: ";
cin>>i;
//pos = linearSearch(arr, i);
n = binarySearch(arr, i);
if(n == -1) {
cout<<i<<" not found in array.";
} else {
cout<<i<<" found at "<<n;
}
return 0;
}