vlambda博客
学习文章列表

C语言-排序算法——插入排序

插入排序(英语:Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

插入排序过程及示意图

代码如下(左边有序,右边无序)

方法1

#include<stdio.h>#include<stdlib.h>#define N 10
void insert_sort(int a[]){ int i, j, temp; for (i = 0; i<N; i++) { for (j = i; j >= 0; j--) { if (a[j - 1]>a[j]) { temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; } } }}int main(){ int a[N] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 }; insert_sort(a); for (int i = 0; i<N; i++) { printf("%d ", a[i]); }
system("pause"); return 0;}

方法2

#include<stdio.h>#include<stdlib.h>#define N 10
void insert_sort(int *s){ for (int i = 1, j, temp; i<N; i++) { temp = s[i]; j = i; while (j >= 0 && temp < s[--j]) { s[j + 1] = s[j]; } s[j + 1] = temp; }}int main(){ int a[N] = { 1, 3, 10, 5, 6, 8, 7, 9, 4, 2 }; insert_sort(a); for (int i = 0; i < N; i++) printf("%d ", a[i]);
puts(""); system("pause"); return 0;}

时间复杂度

  • 最优时间复杂度:O(n) (升序排列,序列已经处于升序状态)

  • 最坏时间复杂度:O(n2)