/*###############
Бинарный поиск
##############################################*/
#include <iostream>
using namespace std;
int main()
{
//Максимальное количество чисел в массиве
const int MAX = 100;
//Максимальное значение чисел
int result[MAX];
//Найденно ли значение?
bool found = false;
//для поиска
int criterion = 0;
int end = MAX - 1, beginning = 0, center;
//Вспомогательная переменная для замены
int exchangeTemp;
//Генератор случайных чисел
srand(time(NULL));
cout << "Binary search" << endl;
for (int index = 0; index < MAX; index++) {
result[index] = rand() % 200;
}
cout << "The unsortieren values are: " << endl;
for (int index = 0; index < MAX; index++)
cout << result[index] << ' ';
cout << endl;
cout << "Now about bubblesort sorting." << endl;
//сортировка
for (int i = 0; i < MAX; i++)
for (int k = 0; k < MAX - i - 1; k++)
if (result[k] > result[k + 1]) {
exchangeTemp = result[k];
result[k] = result[k + 1];
result[k + 1] = exchangeTemp;
}
//отсортированный массив
cout << endl;
cout << "The sorted values are: " << endl;
for (int index = 0; index < MAX; index++)
cout << result[index] << ' ';
cout << endl;
cout << "Search for what? ";
cin >> criterion;
//поиск
while ((end >= beginning) && (found == false)) {
//вычисляем середину
center = (beginning + end) / 2;
if (criterion < result[center])
end = center - 1;
else
if (criterion > result[center])
beginning = center + 1;
else
found = true;
}
if (found == true) {
for (int i = center; i < MAX && result[i] == criterion; ++i)
cout << "The value "<< criterion <<" is at position:" << i << " : " << result[i] << endl;
for (int i = center - 1; i >= 0 && result[i] == criterion; --i)
cout << "The value "<< criterion <<" is at position:" << i << " : " << result[i] << endl;
}
else
cout << "The value "<< criterion <<" was not found. " << endl;
return 0;
}