# 堆排序

void InsertHeap(vector<int>& heap, int node)
{
heap.push_back(node);
int index = heap.size()/2-1;
int index_s = heap.size()-1;
while (index_s > 0 && heap[index] > heap[index_s])
{
int t = heap[index_s];
heap[index_s] = heap[index];
heap[index] = t;
index_s = index;
index = (index_s-1)/2;
}
}

int PopHeap(vector<int>& heap)
{
int result = heap[0];
heap[0] = heap[heap.size()-1];
heap.pop_back();
int index = 0;
int index_s = (index+1)*2-1;
while (index_s < heap.size())
{
if (index_s != heap.size() - 1)
{
if (heap[index]<heap[index_s] && heap[index]<heap[index_s+1])
break;
else if (heap[index_s] > heap[index_s+1])
index_s++;
}
else if (heap[index]<heap[index_s])
break;
int t = heap[index_s];
heap[index_s] = heap[index];
heap[index] = t;
index = index_s;
index_s = (index+1)*2-1;
}
return result;
}

void main()
{
const int k[10] = {5, 3, 7, 8, 1, 2, 0, 9, 6, 4};
vector<int> heap;
for (int i=0;i<10;i++)
InsertHeap(heap, k[i]);
while (!heap.empty())
cout << PopHeap(heap) << endl;
cin.get();
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客