zoukankan      html  css  js  c++  java
  • 排序算法总结

    1、插入排序

    思想:将无需组中的第一个数插入到有序数组中,这样经过N-1次插入即可完成排序。

    C++实现

    #include <IOSTREAM>
    using namespace std;
    void Insert_Sort(int a[],int n);
    
    int main(void)
    {
        int a[] = {1,3,5,5,3,2,4};
        for (int i=0;i<sizeof(a)/sizeof(a[0]);i++)
        {
            cout << a[i] << endl;
        }
    
        Insert_Sort(a,sizeof(a)/sizeof(a[0]));
        cout << "afert sort:" << endl;
    
        for (i=0;i<sizeof(a)/sizeof(a[0]);i++)
        {
            cout << a[i] << endl;
        }
        
        return 0;
    }
    
    void Insert_Sort(int a[],int n)
    {
        for(int i=1;i<n;i++)
        {
            int temp = a[i];
            for (int j=i;j>0;j--)
            {
                if(temp>a[j-1])
                {
                    a[j] = temp;
                    break;
                }
                else
                {
                    a[j] = a[j-1];
                }
    
    
            }
        }
    }

    void Insert_Sort(int *a, int n)
    {
        int key = 0;
        int i, j,k;
        for (k = 0; k < n; k++)
        {
            cout << a[k] << "";
        }
        cout << endl;
    
        for (j = 1; j < n; j++)
        {
            key = a[j];
            i = j - 1;
            while (i >= 0 && key < a[i])
            {
                a[i + 1] = a[i];
                i--;
            }
            a[i + 1] = key;
            
            for (k = 0; k < n; k++)
            {
                cout << a[k] << "";
            }
            cout << endl;
    
    
        }
    }
    
    
    
     

    时间复杂度最坏O(N^2),平均O(N^2),扫描次数N-1.如果是有序数列,则复杂度为O(N-1)。稳定性:稳定

  • 相关阅读:
    HDU 3081 Marriage Match II
    HDU 4292 Food
    HDU 4322 Candy
    HDU 4183 Pahom on Water
    POJ 1966 Cable TV Network
    HDU 3605 Escape
    HDU 3338 Kakuro Extension
    HDU 3572 Task Schedule
    HDU 3998 Sequence
    Burning Midnight Oil
  • 原文地址:https://www.cnblogs.com/wll-zju/p/4236151.html
Copyright © 2011-2022 走看看