一、思路
当插入第i(i>=1)个元素时,前面的V[0], V[1], …,V[i-1]已经排好序。
用V[i]的排序码与V[i-1],V[i-2],…,的排序码顺序进行比较,找到插入位置。然后,将V[i]插入,原来位置上的元素向后顺移。
二、实现程序:
#include <iostream>
using namespace std;
const int maxSize = 100;
// 插入排序
template<typename T>
void insertSort(T arr[], int length) {
for(int i = 1; i < length; i++) {
int temp = arr[i]; // 保存当前位置的值
int j = i - 1;
while(j >= 0 && arr[j] > temp) { // 往前找插入的位置
arr[j+1] = arr[j]; // 往后移
j--;
}
arr[j+1] = temp;
&nb