Muhammad al xorazmiy nomidagi Toshkent Axborot texnologiyalari Universitetinign 310-22 guruh talabasi Booboqulov Samandarning Malumotlar tuzulmasi fanidan Bajargan Mustaqil Ishi
Binar qidiruvdan foydalanib elementlarni tasodifiy ravishda toping.
#include #include #include
int binarySearch(std::vector& arr, int x) {
int bosh = 0;
int oxir = arr.size() - 1;
while (bosh <= oxir) {
int o'rta = bosh + (oxir - bosh) / 2;
if (arr[o'rta] == x) {
return o'rta;
}
else if (arr[o'rta] < x) {
bosh = o'rta + 1;
}
else {
oxir = o'rta - 1;
} }
return -1;}
int main() {
std::vector arr = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };
int x = 30;
std::sort(arr.begin(), arr.end());
std::cout << "Berilgan array: ";
for (int i = 0; i < arr.size(); i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << "Qidirilayotgan element: " << x << std::endl;
int natija = binarySearch(arr, x);
if (natija == -1) {
std::cout << "Element topilmadi" << std::endl;
}
else {
std::cout << "Element indeksi: " << natija << std::endl;
}
return 0;
}
N o'lchamli saralangan massiv berilgan. Foydalanuvchi kiritgan bitta elementni qidirishni interpolyatsion qidirish usulida amalga oshiring.
#include #include #include
int interpolationSearch(std::vector& arr, int x) {
int bosh = 0;
int oxir = arr.size() - 1;
while (bosh <= oxir && x >= arr[bosh] && x <= arr[oxir]) {
int o'rta = bosh + ((double)(oxir - bosh) / (arr[oxir] - arr[bosh])) * (x - arr[bosh]);
if (arr[o'rta] == x) {
return o'rta;
}
else if (arr[o'rta] < x) {
bosh = o'rta + 1;
}
else {
oxir = o'rta - 1;
}
}
return -1;}
int main() {
std::vector arr = { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };
int x = 30;
std::sort(arr.begin(), arr.end());
std::cout << "Berilgan array: ";
for (int i = 0; i < arr.size(); i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
std::cout << "Qidirilayotgan element: " << x << std::endl;
int natija = interpolationSearch(arr, x);
if (natija == -1) {
std::cout << "Element topilmadi" << std::endl;
}
else {
std::cout << "Element indeksi: " << natija << std::endl;
}
return 0;}