Добавить bSearch.cpp
This commit is contained in:
74
bSearch.cpp
Normal file
74
bSearch.cpp
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <ctime>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
void bSort(int arr[], int size) {
|
||||||
|
for (int i = 0; i < size - 1; ++i) {
|
||||||
|
for (int j = 0; j < size - i - 1; ++j) {
|
||||||
|
if (arr[j] > arr[j + 1]) {
|
||||||
|
int temp = arr[j];
|
||||||
|
arr[j] = arr[j + 1];
|
||||||
|
arr[j + 1] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int bSearch(int arr[], int size, int target) {
|
||||||
|
int low = 0;
|
||||||
|
int high = size - 1;
|
||||||
|
|
||||||
|
while (low <= high) {
|
||||||
|
int m = low + (high - low) / 2;
|
||||||
|
|
||||||
|
if (arr[m] == target) {
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
else if (arr[m] < target) {
|
||||||
|
low = m + 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
high = m - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
srand(time(0));
|
||||||
|
setlocale(0, "");
|
||||||
|
|
||||||
|
const int size = 10;
|
||||||
|
int arr[size];
|
||||||
|
|
||||||
|
cout << "Початковий масив: ";
|
||||||
|
for (int i = 0; i < size; ++i) {
|
||||||
|
arr[i] = rand() % 300 + 1;
|
||||||
|
cout << arr[i] << " ";
|
||||||
|
}
|
||||||
|
cout << endl;
|
||||||
|
|
||||||
|
bSort(arr, size);
|
||||||
|
|
||||||
|
cout << "Вiдсортований масив: ";
|
||||||
|
for (int i = 0; i < size; ++i) {
|
||||||
|
cout << arr[i] << " ";
|
||||||
|
}
|
||||||
|
cout << endl;
|
||||||
|
|
||||||
|
int t;
|
||||||
|
cout << "Введiть елемент для пошуку: ";
|
||||||
|
cin >> t;
|
||||||
|
|
||||||
|
int index = bSearch(arr, size, t);
|
||||||
|
|
||||||
|
if (index != -1) {
|
||||||
|
cout << "Елемент знайдено на iндексi (у вiдсортованому масивi): " << index << endl;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
cout << "Елемент не знайдено." << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user