堆排序

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();
}

转载于:https://www.cnblogs.com/RoyCNNK/p/3351404.html

发布了141 篇原创文章 · 获赞 44 · 访问量 19万+
展开阅读全文
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符

没有更多推荐了,返回首页

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

分享到微信朋友圈

×

扫一扫,手机浏览