1. 程式人生 > >【資料結構】堆的應用

【資料結構】堆的應用

1、堆排序

  • 升序建立大頂堆,逆序建立小頂堆。
  • 建堆完畢後,調換堆頂和堆尾元素位置,並且將堆得大小減1
  • 重複第2步,共進行n-1次,排序完成

2、TOP K問題

求最大的前K個元素,建立K大小的小頂堆;求最小的前K個元素,建立K大小的大頂堆。

例1:從海量資料(整數)中找出最大的200個數。

解:

  • 讀入200個數,建立小頂堆
  • 依次讀入後續元素,與堆頂比較,若小於堆頂忽略;如果大於堆頂,則替換堆頂,調整堆。
  • 重複第2步直到讀完為止。堆中的元素即為最大的200個元素,其中堆頂正好是第200大元素

例2:從海量資料(整數)中找出第200大得元素

解:

        解法參見上題。

3、STL partial_sort

partial_sort
<algorithm>

template <class RandomAccessIterator>
  void partial_sort ( RandomAccessIterator first, RandomAccessIterator middle,
                      RandomAccessIterator last );

template <class RandomAccessIterator, class Compare>
  void partial_sort ( RandomAccessIterator first, RandomAccessIterator middle,
                      RandomAccessIterator last, Compare comp );

Partially Sort elements in range
Rearranges the elements in the range [first,last), in such a way that the subrange [first,middle) contains the smallest elements of the entire range sorted in ascending order, and the subrange [middle,end) contains the remaining elements without any specific order.

The elements are compared using operator< for the first version, and comp for the second.

以上是partial_sort的原型說明:部分排序保證在begin和middle之間的元素升序排列,並且該區域的所有元素均小於middle到last區域的元素 -- 即前半段是TOP K的元素,且有序。partial_sort採用上述的TOP K問題解法,不過他多了一步即將建立的堆呼叫一次堆排序以保證最後輸出的前段元素是有序的!

自己實現了一個partial_sort
2007-03-08 13:17
stl那個partial_sort實在不好理解,所以自己實現了一個partial_sort。
功能比較簡單,相對stl的partial_sort只是針對vector<int>做了實現。不過演算法意思和stl的partial_sort是一樣的

typedef std::vector<int>::iterator int_iter;
void partial_sort(int_iter first,int_iter mid,int_iter last)
{
        make_heap(first,mid);   //In fact only [first,mid) is a heap ,so next we begin from mid
        //now *first is the largest in range [first,mid)
        for(int_iter it = mid;it!=last;++it)
        {
                if(*first>*it)
                        swap(*first,*it);
                make_heap(first,mid);
        }
        sort_heap(first,mid);   //we've make heap before
}

partial_sort就是保持[fist,mid)均小於[mid,last),並且[first,mid)是heap,從而實現了部分排序


4、優先順序佇列

無須多言,到處都是。