BUPT-homework/pset10/7-BinarySearchRecursion.c
2021-12-02 19:05:51 +08:00

46 lines
1 KiB
C

#include <stdio.h>
#define MAXN 2000000
int RecurBinarySearch(int a[], int key, int left, int right);
int main() {
int a
[MAXN]; //这个数组比较大,如果在你的电脑中无法分配这么大的内存,请改小后测试。
int n, m, i, key;
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < m; i++) {
scanf("%d", &key);
printf("%d", RecurBinarySearch(a, key, 0, n - 1));
if (i != m - 1)
printf(" ");
else
printf("\n");
}
return 0;
}
/* 请在这里填写答案 */
// --last hope--
#pragma GCC optimize("Ofast,inline") // "Ofast" = "O3,fast-math,allow-store-data-races,no-protect-parens"
int RecurBinarySearch(int a[], int key, int left, int right) {
if (left <= right) {
int mid = (left + right) >> 1;
if (a[mid] == key) { // Base case
return mid;
} else if (a[mid] > key) {
// Search left
return RecurBinarySearch(a, key, left, mid - 1);
} else {
return RecurBinarySearch(a, key, mid + 1, right);
}
} else {
return -1;
}
}