您的位置:首页 > 其它

基础算法 —— 插入排序

2011-08-29 14:58 246 查看
参考书籍:《算法导论》第二版

算法基础 —— 插入排序算法

《算法导论》第二版书中一来就提到了插入排序算法,以扑克牌摸牌来作为比喻,刚开始按照伪代码编写时,

容易忽略一个问题,即用临时变量来实现数组中数据的交换问题。由于该算法确实是算法中最容易理解与掌

握的,所以不作过多解释,以下是代码

#include <iostream>
#include <stdlib.h>
#include <math.h>

using namespace std;

int main(int argc, char *argv[])
{
int array_test[]    = {5, 4, 3, 2, 1, 0};       // 测试数组
int key             = 0;                        // 关键值
int temp            = 0;                        // 临时变量

// 时间复杂度:n^2
for(int j = 1; j < 6; j++ )
{
key = array_test[j];

for(int i = j - 1; i >= 0; i-- )
{
if( array_test[i] > key )
{
// 交换数据
temp = array_test[i + 1];
array_test[i + 1] = array_test[i];
array_test[i] = temp;
}
}
}

// 输出排序后数组
for( int i = 0; i < 6; i++ )
cout << array_test[i] << " ";

cout << endl;
::system("Pause");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: