-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch2.cpp
More file actions
50 lines (41 loc) · 1.06 KB
/
binarySearch2.cpp
File metadata and controls
50 lines (41 loc) · 1.06 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
/*****************
James Bertel
CS111
Lab 6-1
10-30-2017
*****************/
#include <iostream>
using namespace std;
int binarySearch(const int a[], int s, int key);
int main()
{
const int SIZE = 10;
int ar[SIZE] = {90, 80, 70, 60, 50, 40, 30, 20, 10};
int key;
cout << "Enter key: ";
cin >> key;
cout << key << " was found at " << binarySearch(ar, SIZE, key) << endl;
return 0;
}
//This function returns the index where key is found or -1 if key is not found.
//s is the size of the array.
//key is the number being searched for.
int binarySearch(const int a[], int s, int key)
{
int L = 0; //left boudary starts at first index
int r = s-1; //right boundary starts at last index
int m; //middle point between left and right.
//When L and r cross over, search ends. --> key was not found.
while(L <= r)
{
//calculate the middle point between L and r
m = (L + r)/2;
if(a[m] == key) //key was found
return m;
else if(key < a[m])
L = m + 1;
else if(key > a[m])
r = m - 1;
}
return -1; //key wasn't found
}