-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search.cpp
More file actions
70 lines (51 loc) · 1.1 KB
/
binary search.cpp
File metadata and controls
70 lines (51 loc) · 1.1 KB
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
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n;
int arr[10];
cout<<"how many element you want in array:(1-10)"<<endl;
cin>>n;
cout<<" enter an element of arr:"<<endl;
for(int i=0; i<n; i++)
{
cin >>arr[i];
}
//show array
cout<<"your enterd array:\n";
for(int i=0; i<n; i++)
{
cout<<" "<< arr[i];
}
//binary searech
int value;
cout<<"\n enter a value to search in array:";
cin>>value;
int start=0;
int end=n-1;
bool found = false;//initially
while (start <= end)
{
int mid = (start + end) / 2;
if (arr[mid] == value)
{
cout << "Value found at index " << mid << endl;
found = true;
break;
}
else if (arr[mid] < value)
{
start = mid + 1;
}
else
{
end = mid - 1;
}
}
if (!found)
{
cout << "Value not found in the array" << endl;
}
return 0;
}