插入排序

介绍

每次从无序表中取出第一个元素,把它插入到有序表中的合适位置,使有序表仍然有序。

过程

第一趟比较前两个数,然后把第二个数按大小插入到有序表中;

第二趟把第三个数据与前面两个数从后向前比较,插入到合适的位置;

依次进行下去,进行了n-1趟扫描后就完成了整个排序过程。

 

代码

#include<iostream>
using namespace std;


void insertSort(int array[],int length){
    for (int i = 1; i < length; i++){
        if (array[i] < array[i - 1]){
            int temp = array[i];
            int k = i - 1;
            //对已经排好序的部分从后向前遍历,找到插入的位置
            for (int j = k; j >= 0 && temp<array[j]; j--){
                array[j + 1] = array[j];
                k--;
            }
            array[k + 1] = temp;//插入
        }
    }
}
int main(){
    int test[] = { 1, 3, 2, 9, 4, 0, 6, 5, 7, 12, 44, 71, 12 };
    insertSort(test,13);
    for (int i = 0; i < 13; i++){
        cout << test[i] << " ";
    }
    cout << endl;
    return 0;
}

效果:

 

算法分析

时间复杂度:O(n*n)

空间复杂度:O(1)

posted @ 2016-08-12 16:42  bluebean  阅读(186)  评论(0编辑  收藏  举报