二叉堆(C#)
2015-12-17 15:38
696 查看
参考:http://www.cnblogs.com/skywang12345/p/3610390.html
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading; using System.IO; using System.Collections; namespace ConsoleApplication2 { public class Program { public static void Main() { ShowMaxHeap(); ShowMinHeap(); Console.Read(); } private static void ShowMaxHeap() { int[] a = { 10, 40, 30, 60, 90, 70, 20, 50, 80,85 }; BinaryHeap<int> maxHeap = new BinaryHeap<int>((int1, int2) => int1.CompareTo(int2) > 0);//最大推 Console.Write("测试数据:"); for (int i = 0; i < a.Length; i++) { Console.Write(string.Format("{0} ", a[i])); maxHeap.Insert(a[i]); } Console.WriteLine(); Console.WriteLine("最大堆:" + maxHeap); Console.Write("删除元素90:"); maxHeap.Remove(90); Console.WriteLine(maxHeap); } private static void ShowMinHeap() { int[] a = { 80, 40, 30, 60, 90, 70, 10, 50, 20 ,15}; BinaryHeap<int> minHeap = new BinaryHeap<int>((int1, int2) => int1.CompareTo(int2) < 0);//最小推 Console.Write("测试数据:"); for (int i = 0; i < a.Length; i++) { Console.Write(string.Format("{0} ", a[i])); minHeap.Insert(a[i]); } Console.WriteLine(); Console.WriteLine("最小堆:" + minHeap); Console.Write("删除元素10:"); minHeap.Remove(10); Console.WriteLine(minHeap); } } public class BinaryHeap<T> where T : IComparable { private List<T> mHeap; private Func<T, T, bool> comparableFun;//这里我通过用表达式来决定大堆还是小堆 public BinaryHeap(Func<T, T, bool> _comparableFun) { mHeap = new List<T>(); comparableFun = _comparableFun; } public void Insert(T t) { int count = mHeap.Count; mHeap.Add(t); int middle = (count - 1) / 2; T temp = mHeap[count]; while (count > 0 && comparableFun(temp, mHeap[middle]))//temp.CompareTo(mHeap[middle]) < 0 { mHeap[count] = mHeap[middle]; count = middle; middle = (middle - 1) / 2; } mHeap[count] = temp; } public T GetTopAndRemove() { var topT = mHeap[0]; Remove(topT); return topT; } public void Remove(T t) { var index = mHeap.IndexOf(t); int count = mHeap.Count; var temp = mHeap[count - 1]; mHeap.RemoveAt(count - 1); count = count - 1; mHeap[index] = temp; int middle = index * 2 + 1; while (middle < count && !comparableFun(temp,mHeap[middle]))//注意哦 这里多了个取反 { mHeap[index] = mHeap[middle]; index = middle; middle = middle * 2 + 2; } mHeap[index] = temp; } public override String ToString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < mHeap.Count; i++) { sb.Append(mHeap[i] + " "); } return sb.ToString(); } } }
相关文章推荐
- U3D C#脚本的生命周期
- .net平台 .net Framework 组织结构 .net Framework类库 CLR C# 介绍
- 【转】CSharp中的多线程——线程同步基础
- c#自定义控件
- C# eval()函数浅谈
- C#数字格式化
- C#中Socket占用CPU高,解决方案!
- c#监听用户输入调取系统键盘
- C#打开Adobe Reader进程打开pdf并传递页码参数跳转到指定页数
- c#securityexception不允许所请求的注册表访问权
- C#扩展方法实现 byte[] 输出为HEX字符串形式
- C#中判断字符串相等的方法
- C#和.net存在着什么关系
- c# 试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)
- C#泛型委托及约束
- 用C#钩子写一个改键外挂
- 第一章 初始C#
- c#winform datagridview的数据绑定和行的增删改实现
- C#当中的多线程_任务并行库(上)
- C#使用参数数组