Jo’rayev Xudoyshukur 8-variant
------------------------------------------------------------------------------------------
Binar qidiruvdan foydalanib massivdan berilgan kalitga karrali kalitli
elementni va solishtirishlar sonini toping.
------------------------------------------------------------------------------------------
#include
using namespace std;
int steps = 0;
int searchBinary(int arr[], int left, int right, int key){
if(right >= left){
steps++;
int middle = left + (right - left)/2;
if(arr[middle] == key){
return middle;
}
if(arr[middle] > key){
return searchBinary(arr, left, middle - 1, key);
}
return searchBinary(arr, middle + 1, right, key);
}
return -1;
}
int main()
{
int size = 15;
int arr[size];
cout << "Massiv hosil qilindi" << endl;
for(int i = 0; i < size; i++){
arr[i] = i*i + i*i + i;
cout << arr[i] << " ";
}
int key;
cout << "\nKalitni kiriting "; cin >> key;
int result = -1;
int i = 1;
while(true){
i++;
if(key*i > arr[size-1] || result != -1) break;
result = searchBinary(arr, 0, size-1, key*i);
}
if(result == -1){
cout << "Siz kiritgan kalitga karrali element topilmadi" << endl;
return 0;
}
cout << "Siz kiritgan kalitga karrali eng kichik element " << result << "-
indeksdagi " << arr[result] << " soni.\n";
cout << "Solishtirishlar soni " << steps << endl;
return 0;
}
Do'stlaringiz bilan baham: |