插入排序

来源:互联网 发布:淘宝神兽金刚玩具 编辑:程序博客网 时间:2024/06/16 04:07

算法内容是《算法导论》第三版 伪代码的 C 实现

1. 排序算法灵感

We start with insertion sort, which is an efficient algorithm for sorting a small number of elements. Insertion sort works the way many people sort a hand of playing cards. We start with an empty left hand and the cards face down on the table. We then remove one card at a time from the table and insert it into the correct position in the left hand. To find the correct position for a card, we compare it with each of the cards already in the hand, from right to left, as illustrated in Figure 2.1. At all times, the cards held in the left hand are sorted, and these cards were originally the top cards of the pile on the table.

总之排序算法的灵感来自于 扑克牌的理排过程。左手上的牌一直的按照非降序顺序排列的,每插入一个新的数据,和左手里的牌的一一匹配,直到找到合适的位置插入。

这里写图片描述


2. 排序算法的伪代码

Insertion-Sort(A):for j=2 to A.length    key = A[ j ]    // Insert A[j] into the sorted sequence A[1...j-1].    i = j-1     while i > 0 and A[i] > key        A[i+1] = A[i]        i = i - 1    A[i + 1]  = key
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

执行的图示如下:

这里写图片描述


3. 排序算法的C实现

#include <stdio.h> #include <stdlib.h>#define SIZE 10int main(int argc, char const *argv[]){    int arry_int[SIZE];    int i ;    int j ;    int key;    // initialize arry_int rand     for ( i = 0; i < SIZE; i++ )        arry_int[i] = rand()%20;    // print all elements before Insert sort    for ( i = 0; i < SIZE; i++ )        printf("%d\t", arry_int[i] );    printf("\n");    // main loop     for ( j = 1; j < SIZE; j++ )    {        key = arry_int[j];        // compare with elements before j        i = j - 1;        while ( i >= 0 && arry_int[i] > key )        {            // swap i and j elements            arry_int[i+1] = arry_int[i];            i--;        }        arry_int[i+1] = key;    }    // print all elements after Insert sort    for ( i = 0; i < SIZE; i++ )        printf("%d\t", arry_int[i] );    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

结果:

这里写图片描述

$(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('
    ').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i