-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search.cpp
More file actions
62 lines (53 loc) · 1.25 KB
/
binary search.cpp
File metadata and controls
62 lines (53 loc) · 1.25 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
#include <iostream>
using namespace std;
int main()
{
int N, temp, beg, end, mid, target;
cout << "Number of elements: ";
cin >> N;
int array[N];
cout << "Enter the elements: " << endl;
for(int i = 0; i < N; i++)
{
cin >> array[i];
}
for(int i = 0; i < N-1; i++)
{
for(int j = 0; j < N-i-1; j++)
{
if(array[j+1] < array[j])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
cout << "Sorted: " << endl;
for(int i = 0; i < N; i++)
cout << array[i] << endl;
beg = 0;
end = N;
mid = (beg+end)/2;
cout << "Search for number: ";
cin >> target;
while((beg <= end) && (array[mid] != target))
{
if(target < array[mid])
{
end = mid - 1;
mid = (beg+end)/2;
}
else
{
beg = mid + 1;
mid = (beg+end)/2;
}
}
if(array[mid] == target)
cout << "Nuber found!" << endl;
else
cout << "Number not found!" << endl;
system("pause");
return 0;
}