[C++] 数据结构与算法----3.1 实现递归形式的折半查找算法 →→→→→进入此内容的聊天室

来自 , 2019-09-01, 写在 C++, 查看 104 次.
URL http://www.code666.cn/view/6f4920ea
  1. #include <iostream>
  2. using namespace std;
  3. typedef int KeyType;
  4. struct ElemType {KeyType key;};
  5. struct SList {ElemType *r;int length;};
  6.  
  7. int Search_Bin(SList &L,KeyType k);//有序表的折半查找算法
  8. bool ListCreate(SList &L,int n,KeyType a[]);
  9. int ReSea_Bin(SList L,KeyType k,int a,int b);
  10. int ReSea_Bin(SList L,KeyType k);//递归
  11. int main()
  12. {
  13.         SList L; int length=11;
  14.         //KeyType k=1;
  15.         //KeyType k=67;
  16.         KeyType k=67;
  17.         KeyType a[11]={01,03,11,15,17,26,33,45,53,67,72};
  18.         ListCreate(L,length,a);
  19.         cout<<"原顺序表为"<<endl;
  20.         for(int j=0;j<length;j++){cout << L.r[j].key<<"  ";}
  21.         int b=ReSea_Bin(L,k);
  22.         if(b>=0)
  23.                 cout<<"\n在顺序表中"<<k<<"的位置是:"<<b<<endl;
  24.         else
  25.                 cout<<"\n顺序表中未找到"<<k<<endl;
  26.         return 0;
  27. }
  28. int ReSea_Bin(SList L,KeyType k,int a,int b)
  29. {
  30.         int m;
  31.         if(b<a)return -1;
  32.         m=(a+b)/2;
  33.         if(L.r[m].key==k)return m;
  34.         if(L.r[m].key>k)        return  ReSea_Bin(L,k,a,m-1);
  35.         else    return  ReSea_Bin(L,k,m+1,b);
  36. }
  37. int ReSea_Bin(SList L,KeyType k)
  38. {
  39.         int a=0,b=L.length-1;
  40.         return ReSea_Bin(L,k,a,b);
  41. }
  42. int Search_Bin(SList &L,KeyType k)
  43. {
  44.         int a,m,b;
  45.         a=0;b=L.length;
  46.         while(a<=b)
  47.         {
  48.                 m=(a+b)/2;
  49.                 if(L.r[m].key==k)return m;
  50.                 else if(L.r[m].key<k) a=m+1;
  51.                 else b=m-1;
  52.         }
  53.         return -1;
  54. }
  55. bool ListCreate(SList &L,int n,KeyType a[])
  56. {
  57.         int i;
  58.         L.r=new ElemType[n];
  59.         if(!L.r)        return false;
  60.         L.length=n;
  61.         for(i=0;i<n;i++)
  62.         {
  63.                 L.r[i].key=a[i];
  64.         }
  65.         return true;
  66. }

回复 "数据结构与算法----3.1 实现递归形式的折半查找算法"

这儿你可以回复上面这条便签

captcha