-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_using_stl_array.cpp
More file actions
69 lines (45 loc) · 1.63 KB
/
Copy pathbinary_search_using_stl_array.cpp
File metadata and controls
69 lines (45 loc) · 1.63 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
63
64
65
66
67
68
69
/**
* @author: Som Gupta
*/
#include <iostream>
#include <array>
#include <algorithm>
int binarySearch(std::array<int, 5>& arrayReceived, uint key);
int binarySearch(std::array<int, 5>& arrayReceived, uint key) {
//uint returnValue = -1;
std::cout << "INSIDE BINARY SEARCH " << std::endl;
for (int i=0;i<arrayReceived.size();++i)
std::cout << arrayReceived[i] << " ";
std::cout << std::endl;
uint size = arrayReceived.size();
uint startElement = 0u;
uint endElement = (size - 1u);
uint midELement = ((startElement + endElement) /2u);
std::cout << startElement << " " << endElement << " " << midELement << std::endl;
while(startElement <= endElement) {
if (key == arrayReceived[midELement])
return midELement;
if(key > arrayReceived[midELement])
startElement = midELement + 1u;
else
endElement = midELement - 1u;
midELement = ((startElement + endElement) /2u);
}
return -1;
}
int main() {
std::array <int, 5> arrayObj{33,44,11,22,77};
int size = arrayObj.size();
std::cout << "UN-SORTED ARRAY" << std::endl;
for (int i=0;i<size;++i)
std::cout << arrayObj[i] << " ";
std::cout << std::endl;
std::sort(arrayObj.begin(), arrayObj.end());
std::cout << "SORTED ARRAY" << std::endl;
for (int i=0;i<size;++i)
std::cout << arrayObj[i] << " ";
std::cout << std::endl;
int receivedResult = binarySearch(arrayObj, 323);
std::cout << "INDEX is " << receivedResult << std::endl;
return (0);
}