forked from ankurdcruz/CPP-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathADAbinary.cpp
More file actions
48 lines (37 loc) · 1.02 KB
/
ADAbinary.cpp
File metadata and controls
48 lines (37 loc) · 1.02 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
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int a[], int start, int end, int num) {
while(start<=end) {
int mid = (start+end)/2;
if(a[mid]==num)
return mid;
else if(a[mid]<num)
return binarySearch(a,mid+1,end,num);
else
return binarySearch(a,start,mid-1,num);
}
return -1;
}
int main() {
clock_t start, end;
int n, num, a[100];
cout<<"Enter no of elements: ";
cin>>n;
cout<<"Enter elements(in sorted order): ";
for(int i = 0; i<n; i++)
cin>>a[i];
cout<<"Enter number to be found: ";
cin>>num;
start = clock();
int position = binarySearch(a, 0, n-1, num);
if(position == -1)
cout<<"Number not found.\n";
else
cout<<"Number found at index "<<position<<endl;
end = clock();
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(10);
cout << " sec " << endl;
return 0;
}