先来一个迭代版本的:
#include <iostream>
using namespace std;
void main()
{
int a[] = {31,41,59,26,41,58};
for (int i = 1; i < 6; i++)
{
int temp = a[i];
int j = 0;
for (j = i; j > 0; j--)
{
if (a[j-1]>temp)
a[j] = a[j-1];
else
break;
}
a[j] = temp;
}
for (int i = 0; i < 6; i++)
{
cout << a[i] << " ";
cout << endl;
}
system("pause");
}
再来一个递归版本的:
#include <iostream>
using namespace std;
void insertSort(int a[], int n);
void main()
{
int a[] = { 31, 41, 59, 26, 41, 58 };
insertSort(a, 6);
for (int i = 0; i < 6; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
}
void insertSort(int a[], int n)
{
if (n > 1)
{
insertSort(a, n - 1);
int j = 0;
int temp = a[n - 1];
for (j = n - 1; j > 0; j--)
{
if (a[j - 1] > temp)
{
a[j] = a[j - 1];
}
else
break;
}
a[j] = temp;
}
}