非递归插入排序源码
/*************************************************************************
> File Name: insert_sort.c
> Author: wade
> Mail: weideqiong@gmail.com
> Created Time: 2014年01月12日 星期日 04时23分58秒
************************************************************************/
#include<stdio.h>
//打印数组
void show_arry(int a[], int n)
{
int i;
printf("a: ");
for(i = 0; i < n; i++)
{
printf("%d ",a[i]);
}
printf("\n");
return;
}
//非递归方式void insert_sort(int a[], int n) { int i = 0; int j = 0; int key = 0; for(i = 1; i < n; i++) { key = a[i]; j = i-1; while((j >= 0) && (key < a[j])) { a[j+1] = a[j]; j--; } a[j+1] = key; show_arry(a,n); } return; }
//最简单测试int main(void) { int a[] = {9,8,7,6,5,4,3,2,1,0}; int n = sizeof(a)/sizeof(a[0]); show_arry(a,n); insert_sort(a,n); show_arry(a,n); return 0; }
测试结果:
分析与总结(算法导论):
特点:stable sort、In-place sort最优复杂度:当输入数组就是排好序的时候,复杂度为O(n),而快速排序在这种情况下会产生O(n^2)的复杂度。最差复杂度:当输入数组为倒序时,复杂度为O(n^2)插入排序比较适合用于“少量元素的数组”。其实插入排序的复杂度和逆序对的个数一样,当数组倒序时,逆序对的个数为n(n-1)/2,因此插入排序复杂度为O(n^2)。