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
|
#include <iostream>
#include <fstream>
using namespace std;
void bubbleSort(int list[], int listLength);
int binarySearch(int list[], int searchItem, int listLength);
const int LIST_LENGTH = 10;
int main() {
int list[] = {4, 703, 62, 1111, 666, 1337, 9583, 1, 1234, 9999};
int search;
int loc;
bubbleSort(list, LIST_LENGTH);
cout << "Enter the number you wish to search for: ";
cin >> search;
loc = binarySearch(list, search, LIST_LENGTH);
if (loc == -1) {
cout << "The number entered could not be found";
} else {
cout << "The number's location is: " << loc;
}
cout << endl;
/* to check what is currently in list[] */
for (loc = 0; loc < 10; loc++) {
cout << list[loc] << " ";
}
cout << endl;
system("PAUSE");
return 0;
}
void bubbleSort(int list[], int listLength) {
int temp;
for (int it = 0; it < listLength; it++) {
for (int i = 0; i < listLength - it; i++) {
if (list[i] > list[i+1]) {
temp = list[i+1];
list[i+1] = list[i];
list[i] = temp;
} //end if
} //end for
} //end for
} //end bubbleSort
int binarySearch(int list[], int searchItem, int listLength) {
bool found = false;
int min, max, mid;
min = 0;
max = listLength - 1;
while (!found && min <= max) {
mid = (min + max) / 2;
if (list[mid] == searchItem) {
found = true;
} else if (list[mid] > searchItem) {
max = mid - 1;
} else {
min = mid + 1;
} //end if...else
} //end while
if (!found) {
return -1;
} else {
return mid;
} //end if...else
} //end binarySearch
|