From 954a05320003f84586c94a526de78f9ca620e45c Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 2 Dec 2021 19:05:51 +0800 Subject: [PATCH] add binsearches --- pset10/6-BinarySearchIteration.c | 46 ++++++++++++++++++++++++++++++++ pset10/6-binsearch.c | 0 pset10/7-BinarySearchRecursion.c | 45 +++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 pset10/6-BinarySearchIteration.c delete mode 100644 pset10/6-binsearch.c create mode 100644 pset10/7-BinarySearchRecursion.c diff --git a/pset10/6-BinarySearchIteration.c b/pset10/6-BinarySearchIteration.c new file mode 100644 index 0000000..7441d7e --- /dev/null +++ b/pset10/6-BinarySearchIteration.c @@ -0,0 +1,46 @@ +#include + +//函数功能:二分查找 +//函数参数:分别为被查找的数组,数组长度,所查找的元素 +//函数返回值:如果找到,则返回该元素在数组中的下标,否则返回-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; +} diff --git a/pset10/6-binsearch.c b/pset10/6-binsearch.c deleted file mode 100644 index e69de29..0000000 diff --git a/pset10/7-BinarySearchRecursion.c b/pset10/7-BinarySearchRecursion.c new file mode 100644 index 0000000..17d9a5c --- /dev/null +++ b/pset10/7-BinarySearchRecursion.c @@ -0,0 +1,45 @@ +#include + +#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; + } +}