-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBsearch.cpp
More file actions
executable file
·59 lines (49 loc) · 865 Bytes
/
Copy pathBsearch.cpp
File metadata and controls
executable file
·59 lines (49 loc) · 865 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
52
53
54
55
56
57
58
59
#include <iostream>
using namespace std;
int search(int [], int, int);
int main()
{
int array[50], item, size, index;
cout << "Enter size of the array: ";
cin >> size;
for(int i = 0; i < size; i++)
{
cout << "Enter value for index " << i << ": ";
cin >> array[i];
}
cout << "Enter the element to be searched: ";
cin >> item;
index = search(array, size, item);
if(index == -1)
{
cout << "Sorry, element not found.\n";
}
else
{
cout << "Element found at index: " << index << ", position: " << index + 1 << "\n";
}
return 0;
}
int search(int array[], int size, int item)
{
int beg, last, mid;
beg = 0;
last = size - 1;
while(beg <= last)
{
mid = (beg + last) / 2;
if(item == array[mid])
{
return mid;
}
else if(item > array[mid])
{
beg = mid + 1;
}
else
{
last = mid - 1;
}
}
return -1;
}