堆排序
2009-08-02 21:22 Iron 阅读(157) 评论(0) 编辑 收藏 举报//堆排序
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> Heap;
void HeapAdjust(Heap &heap, int start, int end)
{
for(int i = 2*start/*start的左孩子*/; i <= end; i *= 2)
{
if(i < end)
{
//如果孩子的下标没有超过end
//决定与左孩子还是右孩子进行交换
if(heap[i+1] > heap[i])
++i;
}
//如果最大的孩子小于父亲,不进行调换
if(heap[i/2] > heap[i])break;
//与最大的孩子进行调换
swap(heap[i], heap[i/2]);
}
}
void HeapSort(Heap &heap)
{
int i;
//从有孩子的节点开始建堆,单个叶子视为堆
for(i = (heap.size()-1)/2; i>0; --i)
HeapAdjust(heap, i, heap.size()-1);
//把最大的节点与最后一个节点交换,然后重新建堆
for(i = heap.size()-1; i>1; --i)
{
swap(heap[1], heap[i]);
HeapAdjust(heap, 1, i-1);
}
}
int main()
{
Heap heap;
heap.push_back(-1);//[0]处不使用
heap.push_back(1);
heap.push_back(5);
heap.push_back(2);
heap.push_back(4);
heap.push_back(3);
heap.push_back(8);
heap.push_back(6);
HeapSort(heap);
for(int i = 0; i < heap.size(); i++)
cout << heap[i] <<endl;
return 1;
}