插入排序

来源:互联网 发布:淘宝开店会员名大全 编辑:程序博客网 时间:2024/05/16 13:57

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

执行的图示如下:

这里写图片描述


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[]  by rand() function     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 )        {            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;}

结果:

这里写图片描述

原创粉丝点击