插入排序包括直接插入排序、折半插入排序、希尔排序。算法复杂度以及稳定性如下:
一、直接插入排序
#include<stdio.h>
typedef int ElemType;
/* 直接插入排序(使用临时变量) */
void DirectInsertSort_temp(ElemType* a, int len) {
// 排序
int i, j, temp;
for (i = 1; i < len; i++) {
temp = a[i];
if (a[i] < a[i - 1]) {
for (j = i - 1; j >= 0 && temp < a[j]; --j)
a[j + 1] = a[j];
a[j + 1] = temp;
}
}
// 打印排序结果
printf("\n直接插入排序(使用临时变量): ");
for (i = 0; i < len; i++)
printf("%d ", a[i]);
}
/* 直接插入排序(使用哨兵) */
void DirectInsertSort_sentry(ElemType* a, int len) {
// 排序
int i, j;
for (i = 2; i < len; i++) {
a[0] = a[i];
if (a[i] < a[i - 1]) {
for (j = i - 1; a[0] < a[j]; --j)
a[j + 1] = a[j];
a[j + 1] = a[0];
}
}
// 打印排序结果
printf("\n直接插入排序(使用哨兵): ");
for (i = 1; i < len; i++)
printf("%d ", a[i]);
}
int main() {
ElemType a[] = { 12,3,22,1,15,32,88,7,9 };
int a_len = sizeof(a) / sizeof(a[0]);
ElemType b[] = { 0,12,3,22,1,15,32,88,7,9 };
int b_len = sizeof(b) / sizeof(b[0]);
DirectInsertSort_temp(a, a_len);
DirectInsertSort_sentry(b, b_len);
}
二、折半插入排序
#include<stdio.h>
typedef int ElemType;
/* 折半插入排序 */
void BinaryInsertSort(ElemType*a, int len) {
int i, j, low, mid, high;
ElemType temp;
for (i = 1; i < len; i++) {
// 设置折半查找的范围
low = 0;
high = i - 1;
temp = a[i];
// 进入折半查找
while (low <= high) {
// 取中间点
mid = (low + high) / 2;
// 如果小于中间的元素,则查找左半子表
// 否则查找右半子表
if (temp < a[mid])
high = mid - 1;
else
low = mid + 1;
}
// 统一后移元素,空出插入位置
for (j = i - 1; j >= high + 1; j--)
a[j + 1] = a[j];
a[high + 1] = temp;
}
}
/* 打印结果 */
void SortPrint(ElemType* a, int len) {
printf("折半插入排序: ");
for (int i = 0; i < len; i++)
printf("%d ", a[i]);
}
int main() {
ElemType a[] = { 12,3,22,1,15,32,88,7,9 };
int len = sizeof(a) / sizeof(a[0]);
BinaryInsertSort(a, len);
SortPrint(a, len);
}
三、希尔排序
#include<stdio.h>
typedef int ElemType;
/* 希尔排序 */
void ShellSort(ElemType* a, int n) {
int i, j, dk;
ElemType temp;
//增量dk的变化,dk = dk/2
for (dk = n / 2; dk > 0; dk /= 2) {
for (i = dk; i < n; i++) {
//需将a[i]插入有序增量子表中
if (a[i] < a[i - dk]) {
//存到临时变量中
temp = a[i];
for (j = i - dk; j >= 0 && temp < a[j]; j -= dk)
//统一记录后移,查找插入的位置
a[j + dk] = a[j];
a[j + dk] = temp;
}
}
}
}
/* 打印结果 */
void SortPrint(ElemType* a, int len) {
printf("希尔排序: ");
for (int i = 0; i < len; i++)
printf("%d ", a[i]);
}
int main() {
ElemType a[] = { 12,3,22,1,15,32,88,7,9 };
int len = sizeof(a) / sizeof(a[0]);
ShellSort(a, len);
SortPrint(a, len);
}