找元素的時候採用二分查找來提升效率ios
#include <iostream> using namespace std; #define MAXSIZE 20 //順序表的最大長度 typedef struct { int key; char *otherinfo; }ElemType; //順序表的存儲結構 typedef struct { ElemType *r; //存儲空間的基地址 int length; //順序表長度 }SqList; //順序表 void BInsertSort(SqList &L){ //對順序表L作折半插入排序 int i,j,low,high,m; for(i=2;i<=L.length;++i) { L.r[0]=L.r[i]; //將待插入的記錄暫存到監視哨中 low=1; high=i-1; //置查找區間初值 while(low<=high) { //在r[low..high]中折半查找插入的位置 m=(low+high)/2; //折半 if(L.r[0].key<L.r[m].key) high=m-1; //插入點在前一子表 else low=m+1; //插入點在後一子表 }//while for(j=i-1;j>=high+1;--j) L.r[j+1]=L.r[j]; //記錄後移 L.r[high+1]=L.r[0]; //將r[0]即原r[i],插入到正確位置 } //for } //BInsertSort void Create_Sq(SqList &L) { int i,n; cout<<"請輸入數據個數,不超過"<<MAXSIZE<<"個。"<<endl; cin>>n; //輸入個數 cout<<"請輸入待排序的數據:\n"; while(n>MAXSIZE) { cout<<"個數超過上限,不能超過"<<MAXSIZE<<",請從新輸入"<<endl; cin>>n; } for(i=1;i<=n;i++) { cin>>L.r[i].key; L.length++; } } void show(SqList L) { int i; for(i=1;i<=L.length;i++) cout<<L.r[i].key<<endl; } void main() { SqList L; L.r=new ElemType[MAXSIZE+1]; L.length=0; Create_Sq(L); BInsertSort(L); cout<<"排序後的結果爲:"<<endl; show(L); }