栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【数据结构】堆

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构】堆

文章目录
  • 前言
  • 1 代码
  • 总结


前言

C#居然没有堆的数据结构,那就只能自己实现了。

实现参考:《挑战程序设计竞赛》


1 代码

mCompareFunc判断a小于b时为小跟堆,否则为大根堆。

public class Heap
{
     List mHeapList = new List();
     Func mCompareFunc;

     public int Size => mHeapList.Count;

     public Heap(Func compareFunc)
     {
         mCompareFunc = compareFunc;
     }

     public void Push(T value)
     {
         int index = mHeapList.Count;
         mHeapList.Add(value);
         while (index > 0)
         {
             int parent = (index - 1) / 2;
             if (mCompareFunc(mHeapList[parent], value)) break;

             mHeapList[index] = mHeapList[parent];
             index = parent;
         }
         mHeapList[index] = value;
     }

     public T Pop()
     {
         if (Empty())
         {
             throw new ArgumentOutOfRangeException("堆为空!");
         }

         T ret = mHeapList[0];
         int size = mHeapList.Count - 1;
         T x = mHeapList[size];
         int index = 0;
         while(index * 2 + 1 < size)
         {
             int leftChildIndex = index * 2 + 1;
             int rightChildIndex = index * 2 + 2;
             if (leftChildIndex < size && mCompareFunc(mHeapList[rightChildIndex], mHeapList[leftChildIndex])) 
                 leftChildIndex = rightChildIndex;
             
             // 已经没有大小颠倒则退出
             if (!mCompareFunc(mHeapList[leftChildIndex], x)) break;

             mHeapList[index] = mHeapList[leftChildIndex];
             index = leftChildIndex;
         }
         mHeapList[index] = x;
         mHeapList.RemoveAt(mHeapList.Count - 1);
         return ret;
     }

     public T Top()
     {
         return mHeapList[0];
     }

     public bool Empty()
     {
         return mHeapList.Count == 0;
     }
 }
总结

如果要使用优先队列,那么其中一种实现就是把堆封装一下就可以了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1040930.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号