数据结构-查找-二分查找(1)有序表复杂度(lg(n))

来源:互联网 发布:2017淘宝全年的交易额 编辑:程序博客网 时间:2024/05/16 06:14

1.代码区

#include <iostream>
#define MAX 111
using namespace std;
typedef struct{
int key;//关键字
       //other data
} ElemType;
typedef struct{
ElemType *R;//如上
int length;//顺序表长度
} Sstable;
int searchBin(Sstable st, int key);
int main(){
//定义一个顺序表并开辟一个足够的数组空间
Sstable st;
st.R = new ElemType[MAX];
//输入一段有序的序列
cout << "please input sequence length:\n";
cin >> st.length;
cout << "please input sequence elemts:\n";
for(int i = 0; i < st.length; i++){
cin >> st.R[i].key;
}
//调用查找函数
int key;
cout << "please input the number you want to find:\n";
cin >> key;
int index = searchBin(st,key);
//输出查找结果
if(index != 0){
cout << "The number of number subscript to be found is:";
cout << index << endl;
}
else{
cout << "No answer!" << endl;
}
return 0;
}
int searchBin(Sstable st, int key){
//标记下限0上限st.length
int low = 1, high = st.length;
//退出while的条件是当low>high,既在移动的过程当中,low加,high减
while(low <= high){
//每次折中
int mid = (low + high) / 2;
//若等于则查找成功并返回下标
if(key == st.R[mid].key){
return mid;
}
//若查找的值小于序列中间的值
else if(key < st.R[mid].key){
high = mid - 1;
}
//若查找的值大于序列中间的值
else if(key > st.R[mid].key){
low = mid + 1;
}
}
return 0;
}


2.结果区