数据结构_经典查找算法(1)

来源:互联网 发布:鸟倦飞而知还什么意思 编辑:程序博客网 时间:2024/05/20 00:16

线性查找分为:

(1)顺序查找。

(2)折半查找。

查找有两种形态分为:

(1)破坏性查找:此种查找破坏了原来的结构。

(2)非破坏性查找:不破坏结构。


一、顺序查找

平均查找长度  (n+1)/2, 其中n为表长。

#include <iostream>using namespace std;int FindKey(int A[],int len,int key){    for(int i=0;i<len;i++)    {    if(A[i]==key)    return i;//查找成功,返回序列号    }    return -1;//未能查找,返回-1}int main(){int A[10]={1,2,3,4,5,6,7,8,9};int result=FindKey(A,10,5);if(result!=-1)    cout<<"Find the key: "<<result<<endl;else    cout<<"Can't Find the key! "<<endl;return 0;}

二、二分查找(折半查找)

[算法思想]:首先和数组中点比较,如果等于则返回,如果小于中点则在左边区间查找,如果大于中点则在右边区间查找。
  限制:待查表必须是有序的向量(在内存中连续存储)
递归实现:
#include <iostream>using namespace std;int BinarySearch(int A[],int l,int h,int key){int low=l;int high=h;int mid=(low+high)/2;if (low==high&&key!=A[mid]){return -1;}if (key==A[mid]){return mid;}else if (key<A[mid]){mid=mid-1;BinarySearch(A,low,mid,key);} else {mid=mid+1;BinarySearch(A,mid,high,key);}}int main(){int A[10]={3, 7, 9, 10, 11, 24, 45, 66, 77, 123 };int result=BinarySearch(A,0,9,24);if(result!=-1)cout<<"Find the key: "<<result<<endl;elsecout<<"Can't Find the key! "<<endl;system("pause");return 0;}

非递归实现:
#include <iostream>using namespace std;int BinarySearch(int A[],int l,int h,int key){int low=l;int high=h;int mid=(low+high)/2;;while (low<=high && key!=A[mid]){if (key<A[mid]){high=(low+high)/2-1;} else {low=(low+high)/2+1;}         mid=(low+high)/2;}if ( key==A[mid]){return mid;} else{return -1;}}int main(){int A[10]={3, 7, 9, 10, 11, 24, 45, 66, 77, 123 };int result=BinarySearch(A,0,9,3);if(result!=-1)cout<<"Find the key: "<<result<<endl;elsecout<<"Can't Find the key! "<<endl;system("pause");return 0;}

线性查找时间复杂度:O(n);

折半无序(用快排或者堆排)的时间复杂度:O(NlogN)+O(logN);

折半有序的时间复杂度:O(logN);


0 0
原创粉丝点击