1、折半插入
参考书:《数据结构(C语言)》–严蔚敏等编著,清华大学出版社。
在之前我们了解了顺序表的折半查找算法,在这里所使用的折半插入排序也是利用了折半的功能进行排序的;它的思想与直接插入差不多(判断并插入在有序字段中),只不过在查找插入位置的思想上增添了折半查找思想;各种内部排序的比较图见:几大排序比较图
相关代码:
#include "stdio.h"
#include "stdlib.h"
#define OK 1
#define ERROR 0
#define MAXSIZE 20
typedef int Status;
typedef int KeyType;
typedef struct {
KeyType key; //关键字
} RedType;
typedef struct {
RedType r[MAXSIZE+1]; //r.[0]备用或作哨兵或者缓冲区
int length;
} SqList;
Status InitList(SqList &L,int n);
Status InitList(SqList &L,int n) {
int i;
L.length=0;
for(i=1; i<=n; i++) {
scanf("%d",&L.r[i].key);
L.length++;
}
return OK;
}
Status BInsertSort(SqList &L);
//折半插入排序
Status BInsertSort(SqList &L) {
int i,j,low,high,mid;
for(i=2; i<=L.length; ++i) {
L.r[0].key = L.r[i].key; //从第二位开始排序,存储到哨兵中
low = 1;
high = i-1;
while(low <= high) { //折半查找思想:查找high+1的位置
mid = (low + high)/2;
if(L.r[0].key < L.r[mid].key) high = mid-1;
else low = mid+1;
}
for(j=i-1; j>=high+1; --j) //将元素往后移留出high+1的位置
L.r[j+1].key = L.r[j].key;
L.r[high+1].key = L.r[0].key; //将将要排序的关键字插入high+1中
}
}
Status ListPrint(SqList L);
Status ListPrint(SqList L) {
int i;
for(i=1; i<=L.length; i++)
printf("%d ",L.r[i].key);
return OK;
}
int main(void) {
SqList L;
int n;
printf("请输入关键字个数:");
scanf("%d",&n);
printf("请输入无序关键字:");
InitList(L,n);
BInsertSort(L);
printf("折半插入排序的结果为:");
ListPrint(L);
return 0;
}
/*
测试输入:
5
12 33 15 10 8
预期输出:
8 10 12 15 33
测试输入:
10
49 33 15 10 8 77 49 78 88 16
预期输出:
8 10 15 16 33 49 49 77 78 88
测试输入:
9
1 2 3 4 5 6 7 8 9
预期输出:
1 2 3 4 5 6 7 8 9
*/