From a18ee1e5d78f182298c062030f1e277f82faa72a Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Mon, 21 Nov 2022 20:04:27 +0800 Subject: [PATCH] Add bin_search.md --- notes/src/SUMMARY.md | 1 + notes/src/bin_search.md | 57 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 notes/src/bin_search.md diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index 095b11b..50d07d6 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -6,3 +6,4 @@ ## 经典代码 - [合并两个有序链表](./merge_two_sorted_linked_lists.md) +- [二分查找](./bin_search.md) diff --git a/notes/src/bin_search.md b/notes/src/bin_search.md new file mode 100644 index 0000000..f758205 --- /dev/null +++ b/notes/src/bin_search.md @@ -0,0 +1,57 @@ +# 二分查找 + +非递归: + +```cpp +/** + * 二分查找普通实现。 + * @param srcArray 有序数组 + * @param key 查找元素 + * @return 不存在返回-1 + */ +public +static int binSearch(int srcArray[], int key) { + int mid; + int start = 0; + int end = srcArray.length - 1; + while (start <= end) { + mid = (end - start) / 2 + start; + if (key < srcArray[mid]) { + end = mid - 1; + } else if (key > srcArray[mid]) { + start = mid + 1; + } else { + return mid; + } + } + return -1; +} +``` + +递归: + +```cpp +/** + * 二分查找递归实现。 + * @param srcArray 有序数组 + * @param start 数组低地址下标 + * @param end 数组高地址下标 + * @param key 查找元素 + * @return 查找元素不存在返回-1 + */ +public +static int binSearch(int srcArray[], int start, int end, int key) { + int mid = (end - start) / 2 + start; + if (srcArray[mid] == key) { + return mid; + } + if (start >= end) { + return -1; + } else if (key > srcArray[mid]) { + return binSearch(srcArray, mid + 1, end, key); + } else if (key < srcArray[mid]) { + return binSearch(srcArray, start, mid - 1, key); + } + return -1; +} +```