Files
IT-Step/bSearch.cpp
2025-09-23 20:50:24 +03:00

74 lines
1.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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 << "Всортований масив: ";
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;
}