直接插入排序

来源:互联网 发布:中国网络作家排名 编辑:程序博客网 时间:2024/06/06 12:38
#include <iostream>using namespace std;#define MAXSIZE 5typedef int KeyType;typedef struct{KeyType Key[MAXSIZE+1];int length;}SqList;void InsertSort(SqList &L)//直接插入排序{for(int i  = 2; i<= L.length; i++)//需将L.r[i]插入有序子表{if(L.Key[i] < L.Key[i-1]){L.Key[0] = L.Key[i];//复制为哨兵int j;for( j = i-1; L.Key[0]<L.Key[j];--j)L.Key[j+1] = L.Key[j];//记录后移L.Key[j+1] = L.Key[0];//插入到正确的位置}}}void main(){SqList L;L.length = MAXSIZE;for(int i = 1 ; i <= L.length; i++){cin >> L.Key[i];}for(int i = 1; i <= L.length ; i++){cout << L.Key[i] <<" ";}cout << endl;InsertSort(L);for(int i = 1; i <= L.length ; i++){cout << L.Key[i] <<" ";}cout << endl;system("pause");}

原创粉丝点击