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
|
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
void BubbleSort(int array[], int n)
{
if (n < 2)
return;
bool sorted = false;
while (!sorted)
{
sorted = true;
for (int i = 0; i < n - 1; ++i)
{
if (array[i] < array[i + 1]) {
swap(array[i], array[i + 1]);
sorted = false;
}
}
}
}
int binary_search(int array[], int start_index, int end_index, int key)
{
while (start_index <= end_index)
{
int pivot = (start_index + end_index) / 2;
if (array[pivot] == key)
return pivot;
if (key < array[pivot])
end_index = pivot - 1;
else
start_index = pivot + 1;
}
return -1;
}
int main()
{
const int array_size = 25;
int array_to_be_sorted[array_size] =
{
14,65,63,1,54,
89,84,9,98,57,
71,18,21,84,69,
28,11,83,13,42,
64,58,78,82,13
};
BubbleSort(array_to_be_sorted, array_size);
while (true)
{
cout << endl << "Enter a number to find in the sequence: -1 to end" << endl;
int key_search = -1;
cin >> key_search;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (key_search == -1)
break;
int binary_search(int array[], int start_index, int end_index, int key);
// if binaray_searh == -1 "Couldn't find " << keysearch << " in the list" << endl;
//else cout "found" "<< keysearch>>" "at position" "<<_>>" endl;
}
}
|