直接插入排序把待排序序列劃分為「有序序列」與「無序序列」兩部分。每次從無序序列取出第一個元素,從有序序列尾部向前掃描比較,將它插入到合適位置,使有序序列持續增長並保持有序。
#ifndef INSERTSORT_H #define INSERTSORT_H extern void InsertSort(int *pArr, int length); #endif
#include "InsertSort.h"
void InsertSort(int *pArr, int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i - 1;
tmp = *(pArr + i);
while (j >= 0 && tmp < *(pArr + j)) {
*(pArr + j + 1) = *(pArr + j);
j--;
}
if (j != i - 1) {
*(pArr + j + 1) = tmp;
}
}
}
#include "main.h"
int main(void) {
printf("input array length:\n");
int length;
scanf("%d", &length);
if (length <= 0) {
printf("length must be larger 0\n");
return 1;
}
int i;
int arr[length];
for (i = 0; i < length; i++) {
printf("input arr[%d] value:\n", i);
scanf("%d", &arr[i]);
}
printf("arr orig:");
outputArr(arr, length);
InsertSort(arr, length);
printf("arr insert sort completed:");
outputArr(arr, length);
return 0;
}
void outputArr(const int *pArr, const int length) {
int i;
for (i = 0; i < length; i++) {
printf(" %d", *(pArr + i));
}
printf("\n");
}
[root@localhost insertSort]$ gcc -c InsertSort.c [root@localhost insertSort]$ gcc -c main.c [root@localhost insertSort]$ gcc -o main InsertSort.o main.o [root@localhost insertSort]$ ./main
執行後依序輸入元素,即可看到排序前後的對比,例如:
arr orig: 43 65 76 1 43 arr insert sort completed: 1 43 43 65 76
插入排序的最佳時間複雜度為 O(n),最壞為 O(n²),適合排序小規模列表。若列表基本有序,插入排序会比泡沫排序、選擇排序更有效率,是實務中處理「近乎有序」資料的實用選擇。