-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
53 lines (48 loc) · 1.31 KB
/
Copy pathbinarysearch.cpp
File metadata and controls
53 lines (48 loc) · 1.31 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
#include <iostream>
using namespace std;
int binarysearch(int first, int last, int search);
int loadsorteddata();
int id[500];
int total; //number of ID numbers in the array
int search; // the ID number that we are looking for
int index; // index of the ID number we are looking for
int main() {
total = loadsorteddata();
cout << "Enter an id to search for ";
cin >> search;
index = binarysearch(0, total -1, search);
if(index == -1) {
cout << "The id " << search << " is not in the array.\n";
} else {
cout << "The id " << search << " is at index " << index << endl;
}
}
int binarysearch(int first, int last, int search) {
// first = first index, last = last index
int middle, result;
if (first > last) {
return -1; // the base case
}
result = -1;
middle = (first+last) /2;
if (search == id[middle]){
result = middle;
} else if (search >id[middle]) {
result = binarysearch(middle +1, last, search);
} else if (search < id[middle]) {
result = binarysearch(first, middle-1, search);
}
return result;
}
int loadsorteddata(){
int num;
// load data in sorted order - or load randomly sort it
num = 6;
id[0] = 109;
id[1] = 220;
id[2] = 391;
id[3] = 528;
id[4] = 761;
id[5] = 846;
return num;
}