-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search with vector.cpp
More file actions
51 lines (51 loc) · 1004 Bytes
/
binary search with vector.cpp
File metadata and controls
51 lines (51 loc) · 1004 Bytes
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
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> arr;
int size,target,element,mid=0;
bool flag = false;
cout << "Enter the size of Array : " << endl;
cin >> size;
cout << "Array : "<<endl;
for (int i = 0; i < size; i++) {
cin >> element;
arr.push_back(element);
}
int low = 0, high = arr.size() - 1;
cout << "Enter the element to be search : " << endl;
cin >> target;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; low<=high; i++) {
mid =low+(high-low) / 2;
if (arr[mid] == target) {
flag = true;
break;
}
else if (arr[mid] > target) {
high = mid - 1;
}
else if (arr[mid]<target) {
low = mid + 1;
}
else {
flag = false;
}
}
if (flag == true) {
cout << "Number Found";
}
else {
cout << "No Number Found ";
}
return 0;
}