zoukankan      html  css  js  c++  java
  • 堆排序

    优先队列可以用以O(NlogN)时间进行排序,基于该思想的算法叫做堆排序。它给出我们至今所见到的最佳的大O运行时间。

    编码实现如下:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    template <typename Comparable>
    void heapsort( vector<Comparable> &a )
    {
        for ( int i = a.size() / 2 ; i >= 0 ; i-- )         //buildHeap
            percDown( a,i,a.size() );
    
        for ( int j = a.size() - 1 ; j > 0 ; j-- ){         //deleteMax
            swap( a[0],a[j] );
            percDown( a,0,j );
        }
    }
    
    inline int leftChild( int i )
    {
        return 2 * i;
    }
    
    template <typename Comparable>
    void percDown( vector<Comparable> &a,int i,int n )      //进行下滤
    {
        int child;
        Comparable tmp;
    
        for ( tmp = a[i] ; leftChild(i) < n ; i = child ){
            child = leftChild( i );
            if ( child != n - 1 && a[child] < a[ child + 1 ] )
                child++;
            if ( tmp < a[child] )
                a[i] = a[child];
            else
                break;
        }
        a[i] = tmp;
    }
    
    int main()
    {
        cout << "请输入一些数据:" << endl;
    
        vector<int> vec;
        int temp;
    
        while ( cin >> temp )
            vec.push_back( temp );
    
        heapsort( vec );
    
        cout << "按降序排列过的数据如下:" << endl;
    
        vector<int>::iterator iter = vec.begin();
        while( iter != vec.end() )
            cout << *iter++ << endl;
    
        return 0;
    }

     

    我们一路奋战,不是为了改变世界,而是不让世界改变我们 ——《熔炉》
  • 相关阅读:
    Vue中使用WebSocket
    中断「interrupt」(IPI interrupt)
    ARM instruction misc
    ARMV8 datasheet学习笔记4:AArch64系统级体系结构之编程模型(2)- 寄存器
    android logd 原理及实现
    [FTRACE] vmlinux __mcount_loc section
    如何计算eMMC大小
    get the emmc capacity in kernel
    uboot misc
    GPT分区表详解
  • 原文地址:https://www.cnblogs.com/ZRBYYXDM/p/5189496.html
Copyright © 2011-2022 走看看