直接插入排序算法

2014-11-24 00:36:34 · 作者: · 浏览: 43
#include "stdafx.h"
#include
using namespace std;

//直接插入排序算法(升序)
void InsertSort(int a[], int n)
{
int i,j,temp;

//从第二个元素开始,往前面的已经排序的序列插入,插入n-1次
for (i=1; i {
//需要插入排序的元素
temp = a[i];
for (j=i-1; j>=0 && temp < a[j]; j--)
{
a[j+1] = a[j];
}
a[j+1] = temp;
}
}

//输出数组 www.2cto.com
void Print_Arry(int a[], int n)
{
for (int i=0; i {
cout<< a[i]<<" ";
}
cout< }

int _tmain(int argc, _TCHAR* argv[])
{
int a[9] = {7,3,5,8,9,1,2,4,6};
InsertSort(a, 9);
Print_Arry(a, 9);
return 0;
}

摘自 学无止境