add binsearches
This commit is contained in:
parent
155598172c
commit
954a053200
46
pset10/6-BinarySearchIteration.c
Normal file
46
pset10/6-BinarySearchIteration.c
Normal file
|
@ -0,0 +1,46 @@
|
|||
#include <stdio.h>
|
||||
|
||||
//函数功能:二分查找
|
||||
//函数参数:分别为被查找的数组,数组长度,所查找的元素
|
||||
//函数返回值:如果找到,则返回该元素在数组中的下标,否则返回-1
|
||||
int BinarySearch(int a[], int n, int key);
|
||||
|
||||
int main() {
|
||||
int num
|
||||
[2000000]; //这个数组比较大,如果在你的电脑中无法分配这么大的内存,请改小后测试。
|
||||
int n, m, i;
|
||||
int key;
|
||||
|
||||
scanf("%d%d", &n, &m);
|
||||
for (i = 0; i < n; i++)
|
||||
scanf("%d", &num[i]);
|
||||
|
||||
for (i = 0; i < m; i++) {
|
||||
scanf("%d", &key);
|
||||
printf("%d", BinarySearch(num, n, key));
|
||||
if (i != m - 1)
|
||||
printf(" ");
|
||||
else
|
||||
printf("\n");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* 请在这里填写答案 */
|
||||
int BinarySearch(int a[], int n, int key) {
|
||||
int mid;
|
||||
int l = 0, r = n - 1;
|
||||
while (r >= l) {
|
||||
mid = (l + r) / 2;
|
||||
if (a[mid] == key) {
|
||||
return mid;
|
||||
} else if (a[mid] > key) {
|
||||
// Search left
|
||||
r = mid - 1;
|
||||
} else {
|
||||
// search right
|
||||
l = mid + 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
45
pset10/7-BinarySearchRecursion.c
Normal file
45
pset10/7-BinarySearchRecursion.c
Normal file
|
@ -0,0 +1,45 @@
|
|||
#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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue