插入排序用打扑克牌时,摸牌过程的排序来形容比较像:
左手维护一个已排序的序列,右手每次摸一张牌,与左手的牌从后向前进行比较,将这张牌插入到合适的位置,重复该动作直至牌堆的牌被摸完为止。
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。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .