插入排序

算法内容是《算法导论》第三版 伪代码的 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 10

int 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值