-
Notifications
You must be signed in to change notification settings - Fork 0
Binary search
Stas edited this page Mar 5, 2025
·
2 revisions
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 7, 9, 10}; // Posortowany wektor (brak zera!)
int target = 0; // Szukamy liczby, która nie istnieje
int size = vec.size();
int mid = size / 2;
int index1 = 0;
int index2 = size;
cout << "Szukamy liczby: " << target << endl;
while (index1 < index2) {
cout << "index1: " << index1 << ", index2: " << index2 << ", mid: " << mid << ", vec[mid]: " << vec[mid] << endl;
if (vec[mid] == target) {
cout << "Znaleziono " << target << " na indeksie " << mid << endl;
return 0;
}
if (vec[mid] < target) {
cout << "Szukamy w prawej części" << endl;
index1 = mid + 1;
} else {
cout << "Szukamy w lewej części" << endl;
index2 = mid;
}
mid = (index1 + index2) / 2;
}
cout << "Element " << target << " nie istnieje w wektorze." << endl;
return 0;
}