3-插入排序

3.插入排序 

最好的情况下 本来就是1 2 3 4 5  比较次数为n-1  次移动次数为 0 

最坏的情况下 本来就是 5 4 3 2 1 比较次数为2+3+4+...+n=(n+2)(n-1)/2,    移动次数为(n+4)(n-1)/2

时间复杂度也为O(n^2)

#include <iostream>
using namespace std;
void InsertSort(int *a, int n)
{
    for(int i=1;i<n;i++)
    {
        if(a[i]<a[i-1])
        {
            int j = i-1;
            int temp = a[i];   //把待排序元素赋给temp,temp在while循环中并不改变,这样方便比较,并且它是要插入的元素
            while((j>=0)&&(temp<a[j]))     //while循环的作用是将比当前元素大的元素都往后移动一个位置
            {
                a[j+1]=a[j];
                j--;   // 顺序比较和移动,依次将元素后移动一个位置
            }
            a[j+1] = temp;    //元素后移后要插入的位置就空出了,找到该位置插入
        }
    }
}

void InsertSort(int *a, int n)  
{  
    for(int i=1; i<n;i++)  
    {  
        if(a[i]<a[i-1])  
        {  
            int temp = a[i];  
            int j=i-1;  
            for(;j>=0 && temp<a[j];j--)  
            {  
                a[j+1] = a[j];  
            }  
            a[j+1] = temp;  
        }  
    }  
}  

int main()
{
    int a[6] = {1,5,3,4,6,2};
    BubbleSort(a,6);
    for(int i=0;i<6;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
    return 0;
}


posted @ 2017-03-07 17:26  sowhat1412  阅读(77)  评论(0编辑  收藏  举报