插入排序

插入排序(Insertion Sort)的基本思想是:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子序列中的适当位置,直到全部记录插入完成为止。

 

 

#include <iostream>

using namespace std;

void InsertionSort(int *a,int size)
{
    for(int i = 1; i < size; i++)
    {
        int tmp = a[i];
        int k ;
        for( k = i-1; k >= 0&&a[k] > tmp; k--)
        {
            a[k+1] = a[k];
        }

        a[k+1] = tmp;

    }

}
int main()
{
    int arr[6] = {22,3,1,44,3,9};
    InsertionSort(arr,6);
    for(int i = 0; i < 6; i++ )
    cout << arr[i] << " ";
    return 0;
}

  时间复杂度O(n^2)

  插入排序是稳定的排序方法。

posted @ 2016-09-07 16:32  prog123  阅读(164)  评论(0编辑  收藏  举报