插入排序——Insertion Sort
C/C++ 代码:
#include <iostream>
#include <stdlib.h>
using namespace std;
void Print( int r[], int n )
{
for( int i = 0; i < n; i++ )
{
cout << r[i] << " ";
}
cout << endl;
}
void InsertionSort( int r[], int n )
{
int temp, i, j;
for( i = 0; i < n; i++ )
{
temp = r[i];
for( j = i - 1; j >= 0 && r[j] > r[j+1]; j-- )
{
r[j+1] = r[j];
}
r[j+1] = temp;
}
}
int main()
{
int r[] = { 34, 12, 45, 78, 52, 18, 67, 90, 64, 72, 27 };
int n = sizeof( r ) / sizeof( int );
Print( r, n );
InsertionSort( r, n );
Print( r, n );
system( "PAUSE" );
return 0;
}