插入排序

GitHub

插入排序用打扑克牌时,摸牌过程的排序来形容比较像:

左手维护一个已排序的序列,右手每次摸一张牌,与左手的牌从后向前进行比较,将这张牌插入到合适的位置,重复该动作直至牌堆的牌被摸完为止。

 

python代码:

def InsertionSort(A):
    for j in range(1, len(A)):
        key = A[j]
        i = j - 1
        while i >= 0 and A[i] > key:
            A[i+1] = A[i]
            i = i - 1
        A[i+1] = key


A = [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
print(A)
InsertionSort(A)
print(A)

输出:

[Running] python -u "e:\WorkSpace\Python\Introduction to Algorithms\Chapter2\InsertionSort.py"
[2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[Done] exited with code=0 in 0.048 seconds

 

C++代码:

#include "InsertionSort.h"
#include "Common.h"
#include <iostream>
using namespace std;

void InsertionSort(int* a, int len)
{
    for (int j = 1; j < len; j++)
    {
        int key = a[j];
        int i = j;
        while (--i >= 0 && a[i]> key)
        {
            a[i + 1] = a[i];
        }
        a[i + 1] = key;
    }
}

void TestInsertionSort()
{
    int a[] = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 };
    int len = sizeof(a) / sizeof(int);
    InsertionSort(a, len);
    Print(a, len);
}

输出:

1  2  3  4  5  6  7  8  9  10

E:\WorkSpace\C++\Introduction to Algorithms\Introduction to Algorithms\Debug\Introduction to Algorithms.exe (进程 25608)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值