Misol uchun : 1.
#include
// Rekursiyali qidiruv funksiyasi. U massivdan
// x qaysi o'rinda turganini qaytaradi,
// yoki -1
int binarqidiruv(int arr[], int l, int r, int x) {
if (r >= l)
{
int mid = l + (r - l)/2;
// Agar element x ga teng bo'lsa
// o'zi qaytadi
if (arr[mid] == x)
return mid;
// Agar element x dan katta bo'lsa,
// u faqat chap qismni oladi
if (arr[mid] > x)
return binarqidiruv(arr, l, mid-1, x);
// Yoki u faqat o'ng qismni oladi
return binarqidiruv(arr, mid+1, r, x);
}
// Bu yerga yetib keladi, qachonki
// x soni massiv ichidan topilmasa
return -1;
} int main(void) {
int arr[] = {2, 3, 4, 10, 40};
//massiv ni elementlar sonini topib olayabmiz
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int natija = binarqidiruv(arr, 0, n-1, x);
(natija == -1)? printf("X soni massivni ichidan topilmadi.")
: printf("X soni massivning %d - elementi.",
natija);
return 0;
}
2.
#include using namespace std; int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2;
if (arr[mid] == x) if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x); }
return -1; }
int main(void) { int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); int result = binarySearch(arr, 0, n - 1, x); (result == -1) ? cout << "Element is not present in array" : cout << "Element is present at index " << result; return 0; }
Do'stlaringiz bilan baham: |