《数据结构Chapter10·内部排序》

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define MAXSIZE 20
typedef int Keytype;
typedef struct{
Keytype key;
// char *otherinfo;
}Redtype;

typedef struct{
Redtype r[MAXSIZE + 1];
int length;
}SqList;

//int a, b;
#define EQ(a, b) ((a) == (b))
#define LT(a, b) ((a) < (b))
#define LQ(a, b) ((a) <= (b))
/*
char *aa, *bb;
#define EQ(aa, bb) (!strcmp(aa, bb))
#define LT(aa, bb) (strcmp(aa, bb) < 0)
#define LQ(aa, bb) (strcmp(aa, bb) <= 0)
*/
void InsertSort(SqList &L);
void BInsertSort(SqList &L);

int Print(SqList L)
{
int i;
for(i = 1; i <= L.length; i ++)
printf("%d ", L.r[i]);
printf("\n");
return 0;
}

int main()
{
SqList L1 = {{0 ,3, 4, 6, 2, 1, 5, 8, 9, 0, 7}, {10}};
SqList L2 = L1;
InsertSort(L1);
Print(L1);
BInsertSort(L2);
Print(L2);
system("pause");
return 0;
}



//三句口诀背诵插入排序
void InsertSort(SqList &L) { // 算法10.1 // 对顺序表L作直接插入排序。
int i,j;
for (i=2; i<=L.length; ++i)
if (LT(L.r[i].key, L.r[i-1].key)) {// "<"时,需将L.r[i]插入有序子表 //TOM// i > i - 1,
L.r[0] = L.r[i]; // 复制为哨兵
for (j=i-1; LT(L.r[0].key, L.r[j].key); --j) //TOM//0 < j
L.r[j+1] = L.r[j]; // 记录后移 //TOM //主角j+1
L.r[j+1] = L.r[0]; // 插入到正确位置 //TOM//主角j+1
}
} // InsertSort

void BInsertSort(SqList &L) { // 算法10.2 // 对顺序表L作折半插入排序。
int i, j, high, low, m;
for (i=2; i<=L.length; ++i) {
L.r[0] = L.r[i]; // 将L.r[i]暂存到L.r[0]
low = 1;
high = i-1;
while (low<=high) { // 在r[low..high]中折半查找有序插入的位置
m = (low+high)/2; // 折半
if (LT(L.r[0].key, L.r[m].key)) high = m-1; //TOM 0 < m // 插入点在低半区
else low = m+1; // 插入点在高半区
}
for (j=i-1; j>=high+1; --j) //TOM for (j=i-1; LT(L.r[0].key, L.r[j].key); --j) 亦可
L.r[j+1] = L.r[j]; // 记录后移
L.r[j + 1] = L.r[0]; //TOM  L.r[high+1] = L.r[0]; 亦可 // 插入
}
} // BInsertSort
posted on 2012-02-20 09:40  tomctx  阅读(165)  评论(0编辑  收藏  举报