-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbinary_search.cpp
44 lines (40 loc) · 899 Bytes
/
binary_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
// Binary Search Program: Time Complexity - O(nlogn).
#include <iostream>
using namespace std;
int main()
{
int count, i, arr[30], num, first, last, middle;
cout<<"how many elements would you like to enter?:";
cin>>count;
for (i=0; i<count; i++)
{
cout<<"Enter number "<<(i+1)<<": ";
cin>>arr[i];
}
cout<<"Enter the number that you want to search:";
cin>>num;
first = 0;
last = count-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < num)
{
first = middle + 1;
}
else if(arr[middle] == num)
{
cout<<num<<" found in the array at the location "<<middle+1<<"\n";
break;
}
else {
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<num<<" not found in the array";
}
return 0;
}