插入排序实现

#include 
using namespace std;
template <class T>
void insertSort(T a[],int n)
{
    for(int i = 1;i < n;i++)
    {
        int j = i;
        T tem = a[i];
        while(j > 0 && tem < a[j-1])
        {
            a[j] = a[j-1];
            j--;
        }
        a[j] = tem;
        for(int i = 0;i < n;i++)
            cout << a[i] << " ";
        cout << endl;
    }
}
int main()
{
    int a[] = {1,9,4,9,1,0,0,1};
    insertSort(a,8);
}

输出结果:

1 9 4 9 1 0 0 1 
1 4 9 9 1 0 0 1 
1 4 9 9 1 0 0 1 
1 1 4 9 9 0 0 1 
0 1 1 4 9 9 0 1 
0 0 1 1 4 9 9 1 
0 0 1 1 1 4 9 9 

你可能感兴趣的:(#,C++编程)