插入排序演算法
直接運行即可
#include <iostream>
using namespace std;
#define MAXSIZE 20 //順序表的最大長度
typedef struct
{
int key;
char *otherinfo;
}ElemType;
//順序表的存盤結構
typedef struct
{
ElemType *r; //存盤空間的基地址
int length; //順序表長度
}SqList; //順序表型別
void InsertSort(SqList &L)
{
//對順序表L做直接插入排序
int i,j;
for(i=2;i<=L.length;++i)
if(L.r[i].key<L.r[i-1].key)
{ //"<",需將r[i]插入有序子表
L.r[0]=L.r[i]; //將待插入的記錄暫存到監視哨中
L.r[i]=L.r[i-1]; //r[i-1]后移
for(j=i-2; L.r[0].key<L.r[j].key;--j) //從后向前尋找插入位置
L.r[j+1]=L.r[j]; //記錄逐個后移,直到找到插入位置
L.r[j+1]=L.r[0]; //將r[0]即原r[i],插入到正確位置
} //if
} //InsertSort
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;
}
int main()
{
SqList L;
L.r=new ElemType[MAXSIZE+1];
L.length=0;
Create_Sq(L);
InsertSort(L);
cout<<"排序后的結果為:"<<endl;
show(L);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/115746.html
標籤:其他
下一篇:排序-拆半插入排序
