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; +} +```