您的位置:首页 > 其它

插入排序之2路插入排序

2014-08-22 09:36 204 查看
#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 20
#define SIZE 100

typedef int KeyType ;
typedef char InfoType ;

typedef struct {
KeyType key ;
InfoType otherInfo ;
}RedType;//记录的类型

typedef struct{
RedType r[MAXSIZE+1] ;//0号单元设置哨兵
int length ;  //顺序表的长度
}SqList;
/*2路插入排序算法
基本思想:
1.将L.r[1].key赋值给d[1],将d[1]看成是排序中间的记录
2.将L.r[2].key 与d[1]比较,根据与d[1]的比较结果,插入到d[1]的前面或是后面
将d看成一个循环向量,设置两个指针first,final,分别指向d的第一个元素和最后一个元素
//1.建立和L.r 同类型的数组
*/
void TwoWayInsertSort(SqList &L,RedType d[MAXSIZE] ){

d[1] = L.r[1];                 //将L中的第一个元素放置在d数组的第一个位置
int first=1 ,final =1;          //初始化first,final

for(int i =2;i<=L.length;i++){
if(L.r[i].key>d[1].key){ //插到后面
for(int k = final ;d[k].key>L.r[i].key;k--){
d[k+1]=d[k] ;
}
d[k+1]=L.r[i];
final = (final+1)%MAXSIZE ;
}else{ //插到前面
for(int h=first;d[h].key>L.r[i].key;h++){
d[h-1]=d[h];
}
first=(first-1+MAXSIZE)%MAXSIZE;
d[h+1] = L.r[i];
}
}

}
<pre name="code" class="cpp">void PrintD(RedType  d[]){
for(int i=1;i<=8;i++){
printf("%d\t",d[i].key);
}
}




void main(){
SqList L ;
L.r[1].key = 49 ;
L.r[2].key = 38 ;
L.r[3].key = 65 ;
L.r[4].key = 97 ;
L.r[5].key = 45 ;
L.r[6].key = 13 ;
L.r[7].key = 27 ;
L.r[8].key = 49 ;
L.length = 8;

printf("--------------------------------------------------------------\n");
RedType d[MAXSIZE] ;
TwoWayInsertSort(L,d) ;
printf("2路插入排序\n");
PrintD(d);
printf("\n");
printf("--------------------------------------------------------------\n");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: