zoukankan      html  css  js  c++  java
  • 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;
    }


    关注公众号 海量干货等你
  • 相关阅读:
    Redis学习笔记(九、Redis总结)
    菜鸟刷面试题(二、RabbitMQ篇)
    RabbitMQ学习笔记(八、RabbitMQ总结)
    MongoDB学习笔记(七、MongoDB总结)
    菜鸟刷面试题(一、Java基础篇)
    朋友圈点赞
    队列变换
    犯二的程度
    猴子选大王
    最大销售增幅
  • 原文地址:https://www.cnblogs.com/sowhat1412/p/12734489.html
Copyright © 2011-2022 走看看