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、优先级队列
无须多言,到处都是。


8781

被折叠的 条评论
为什么被折叠?



