-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02_binarySearch.cpp
executable file
·81 lines (71 loc) · 1.69 KB
/
02_binarySearch.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
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
71
72
73
74
75
76
77
78
79
80
81
/**
* @file binarySearch.cpp
* @author Muhib Arshad(@muhib7353 at everyone)
* @brief Time Complexity: have worst case O(log n) and best case O(1)
* @e https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/binary_search.cpp
* @date 2023-01-23
*/
#include <iostream>
#include <algorithm>
using namespace std;
int binarySearch(int *&arr, const int &size, const int &ele)
{
int first = 0;
int last = size - 1;
int middle = 0;
while (first <= last)
{
middle = (first + last) / 2;
if (ele < arr[middle])
last = middle - 1;
else if (ele > arr[middle])
first = middle + 1;
else
return middle;
}
throw("Such Element does not exist");
}
void input(int *&arr, const int &size)
{
cout << "Enter the elements in the array:\n";
for (int i = 0; i < size; i++)
{
cout << "Enter the element no " << i + 1 << " : ";
cin >> *(arr + i);
}
}
void output(int *&arr, const int &size)
{
cout << "The elements in the array:\n";
for (int i = 0; i < size; i++)
{
cout << *(arr + i) << " ";
}
cout << "\n";
}
int main()
{
int size, ele, index = -1;
cout << "Enter the size :";
cin >> size;
int *arr = new int[size];
input(arr, size);
sort(arr, arr + size);
output(arr, size);
try
{
cout << "Enter the element that you want to search its index position:\n";
cin >> ele;
index = binarySearch(arr, size, ele);
}
catch (const char *str)
{
cout << str << "\n";
}
if (index >= 0)
{
cout << "The index position of element = " << index << "\n";
}
delete[] arr;
return 0;
}