1、设定待排序的数据保存在数组data[]中
2、设置外层循环,即从第二个数据到最后一个数据。(只有一个数据则为考虑为已经是有序的,所以循环从第二个数据开始)其中n为待排序数据的长度。
3、定义一个用来临时保存将要进行插入操作的元素temp。
4、编写内层循环,寻找插入位置并移动元素。
5、将tmp插入到寻找到的位置j+1
6、最后附上全部运行代码及运行截图#include "stdafx.h"#include <iostream>using namespace std;template <class T>void outputArr(T&,int);int main(){ int i, j; int data[] = { 23, 98, 7, 28, 92, 14, 89, 1 };//共8个数据 int n = sizeof(data) / sizeof(data[0]); cout << "排序前的结果:\n"; outputArr(data, n); for ( i = 1; i < n;i++) { int temp = data[i]; for ( j = i - 1; j >= 0 && data[j]>temp;j--) { data[j + 1] = data[j]; } data[j + 1] = temp; } cout << "排序后的结果:\n"; outputArr(data, n); return 0;}template <class T>void outputArr(T &a,int n){ for (int i = 0; i < n;i++) { cout << a[i] << " "; } cout << endl;}
7、可以通过引入哨兵来将算法改进,避免了边界检查。即将数组的第一个位置替换上面的temp临时变量。