直接插入排序是简单排序,把待排序的数组看成是两个数组,一个是已经排好序的数组,一个待排序的数组
下面的程序是从后往前
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
void InsertSort(int *arr, int length)
{
for (int i = 1; i < length; i++)
{
int temp = arr[i];
int j;
for (j = i, j > 0; arr[j - 1] > temp; j--)
{
arr[j] = arr[j-1];
}
arr[j] = temp;
}
}
int main()
{
srand(time(nullptr));
int nArr[10];
for (int i = 0; i < 10; i++)
{
nArr[i] = rand() % 100;
}
cout << "排序前:" << endl;
for (int i = 0; i < 10; i++)
{
cout << nArr[i] << " " << endl;
}
cout << endl;
cout << "排序后:" << endl;
InsertSort(nArr, 10);
for (int i = 0; i < 10; i++)
{
cout << nArr[i] << " " << endl;
}
}