Files
2022-WangDao-CS-DS-Notes/7.3折半查找.md
2022-03-29 11:49:34 +08:00

65 lines
2.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 折半查找——Binary Search
### 一、折半查找的定义
`折半查找`,又叫`二分查找`。仅适用于`有序的顺序表`
### 二、折半查找的实现
`算法思想`:每次从中间分,判断自己是哪一半
普通代码:
```c
//查找表的数据结构(动态分配的顺序表)
typedef struct{
ElemType *elem; //指向“动态”分配的数组的指针
int TableLen; //查找表的当前长度
}SSTable;
//折半查找
int Binary_Search(SSTable L, ElemType key){
int low =0, high = L.TableLen-1, mid;
while(low <= high){
mid = (low + high)/2; //取中间值
if(L.elem[mid] == key){
return mid; //查找成功,则返回所在位置
}else if(L.elem[mid] > key){
high = mid - 1; //从前半部分继续查
}else{
low = mid + 1; //从后半部分继续查
}
}
return -1; //查找失败,返回-1
}
```
### 三、查找效率分析
![uTools_1638256115837](https://github.com/oxyanyano/2022-WangDao-CS-DS-Notes/blob/main/images/uTools_1638256115837.png)
### 四、折半查找判定树的构造
#### 构造:
![uTools_1638256209356](https://github.com/oxyanyano/2022-WangDao-CS-DS-Notes/blob/main/images/uTools_1638256209356.png)
![uTools_1638256305668](https://github.com/oxyanyano/2022-WangDao-CS-DS-Notes/blob/main/images/uTools_1638256305668.png)
![uTools_1638256324365](https://github.com/oxyanyano/2022-WangDao-CS-DS-Notes/blob/main/images/uTools_1638256324365.png)
#### 特性:
![uTools_1638256454841](https://github.com/oxyanyano/2022-WangDao-CS-DS-Notes/blob/main/images/uTools_1638256454841.png)
查找表有n个关键字则失败结点有n+1个
![uTools_1638256551359](https://github.com/oxyanyano/2022-WangDao-CS-DS-Notes/blob/main/images/uTools_1638256551359.png)
`折半查找判定树`的高度h有关。高度越小查找效率越高
最好情况,平均查找长度=$$O(log_2n)$$
最坏情况,平均查找长度=$$O(n)$$
`时间复杂度`=$$O(log_2n)$$