插入排序(Insertion Sort):
适用于数目较少的元素排序
伪代码(Pseudocode):
例子(Example):
符号(notation):
时间复杂度(Running Time):
源代码(Source Code):
#include <iostream>
using namespace std;
//升序排序
void InsertSort(int a[], int n) {
for (int j = 1; j < n; j++)
{
int temp = a[j];
int i = j - 1;
while (i >= 0 && a[i] > temp)
{
a[i + 1] = a[i];
i--;
}
a[i + 1] = temp;
}
}
void display(int a[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
void main()
{
int a[100] = { 0 };
for (int k = 0; k < 20; k++)
{
for (int i = 0; i < 100; i++)
{
a[i] = rand() % 1000;
}
printf("\n before sort:\n");
display(a, 100);
InsertSort(a, 100);
printf("\n after sort:\n");
display(a, 100);
}
system("pause");
}