把算法导论第六章的堆排序用C#实现了一下。 把MaxHeapify用迭代实现了。发现几个问题:
第一呢,算法导论中假设内部数组是从1开始的,结果左右结点的算法和从0开始的数组实际上是不同的。
第二呢,在改迭代的时候,粗心把循环变量写错了。结果调了很久,郁闷死。
并且加入优先级队列的功能,包括Maximum, ExtractMax, IncreaseKey, Insert, Delete子过程
下面是实现的代码:
namespace FengChen.Practices
{
public class Chapter6
{
public class MaxHeap
{
private Int32[] m_Array;
private Int32 m_Size;

heap tree node navigation

public Int32 Size { get { return m_Size; } }

public MaxHeap(Int32 size)
{
m_Array = new Int32[size];
m_Size = Size;

BuildMaxHeap();
}

public MaxHeap(Int32[] inputArray)
{
if (inputArray == null)
throw new ArgumentNullException("inputArray", "The input Array cannot be null!");
m_Array = inputArray;
m_Size = inputArray.Length;

BuildMaxHeap();
}

public String Show()
{
// List the current heap elements
return Common.ListTheArray(m_Array);
}

6.2 Maintaining the heap property

6.3 Building a max heap

Veriry a max heap

6.4 The heapsort algorithm(Sort to non-increasing order)

6.5 Priority queues
}
}
}
第一呢,算法导论中假设内部数组是从1开始的,结果左右结点的算法和从0开始的数组实际上是不同的。
第二呢,在改迭代的时候,粗心把循环变量写错了。结果调了很久,郁闷死。
并且加入优先级队列的功能,包括Maximum, ExtractMax, IncreaseKey, Insert, Delete子过程
下面是实现的代码:
namespace FengChen.Practices
{
public class Chapter6
{
public class MaxHeap
{
private Int32[] m_Array;
private Int32 m_Size;
heap tree node navigation
public Int32 Size { get { return m_Size; } }
public MaxHeap(Int32 size)
{
m_Array = new Int32[size];
m_Size = Size;
BuildMaxHeap();
}
public MaxHeap(Int32[] inputArray)
{
if (inputArray == null)
throw new ArgumentNullException("inputArray", "The input Array cannot be null!");
m_Array = inputArray;
m_Size = inputArray.Length;
BuildMaxHeap();
}
public String Show()
{
// List the current heap elements
return Common.ListTheArray(m_Array);
}
6.2 Maintaining the heap property
6.3 Building a max heap
Veriry a max heap
6.4 The heapsort algorithm(Sort to non-increasing order)
6.5 Priority queues
}
}
}
本文分享了使用C#实现《算法导论》第六章中的堆排序算法的过程,并加入了迭代实现MaxHeapify的方法。此外还实现了优先级队列的各种操作,如插入、删除最大值等。

307

被折叠的 条评论
为什么被折叠?



