Add bin_search.md

This commit is contained in:
Sainnhe Park 2022-11-21 20:04:27 +08:00
parent 0a13bff07b
commit a18ee1e5d7
2 changed files with 58 additions and 0 deletions

View File

@ -6,3 +6,4 @@
## 经典代码
- [合并两个有序链表](./merge_two_sorted_linked_lists.md)
- [二分查找](./bin_search.md)

57
notes/src/bin_search.md Normal file
View File

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