• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C# 实现堆排序算法代码

OC/C/C++ 水墨上仙 1988次浏览

C# 实现堆排序算法代码

1.&nbsp什么是堆?可以想像成一个二叉树,对于每一个结点,如果父结点比左右孩子都大叫大顶堆,如果比左右孩子小叫小顶堆。堆不一定要用树来表示,也可以用普通的数组来表示,如果数组索引从1开始,那么索引为i的结点的左右孩子的索引分别为2i和2i+1。2.&nbsp堆排序它比简单插入排序的优点是简单插入排序为了从R[1..n]中选出关键字最小的记录,必须进行n-1次比较,然后在R[2..n]中选出关键字最小的记录,又需要做n-2次比较。事实上,后面的n-2次比较中,有许多比较可能在前面的n-1次比较中已经做过,但由于前一趟排序时未保留这些比较结果,所以后一趟排序时又重复执行了这些比较操作。&nbsp堆排序可通过树形结构保存部分比较结果,可减少比较次数。基本思想&nbsp1、先将数组R[1..n]建成一个大根堆,此堆为初始的无序区&nbsp2、再将关键字最大的记录R[1](即堆顶)和无序区的最后一个记录R[n]交换,由此得到新的无序区R[1..n-1]和有序区R[n],且满足R[1..n-1].keys≤R[n].key&nbsp3、由于交换后新的根R[1]可能违反堆性质,故应将当前无序区R[1..n-1]调整为堆。然后再次将R[1..n-1]中关键字最大的记录R[1]和该区间的最后一个记录R[n-1]交换,由此得到新的无序区R[1..n-2]和有序区R[n-1..n],且仍满足关系R[1..n-2].keys≤R[n-1..n].keys,同样要将R[1..n-2]调整为堆。&nbsp4、重复第3步直到整个数组有序。算法如下:void&nbspHeapSort(SeqIAst&nbspR)&nbsp{&nbsp//对R[1..n]进行堆排序,不妨用R[0]做暂存单元&nbspint&nbspi;&nbspBuildHeap(R);&nbsp//将R[1-n]建成初始堆&nbspfor(i=n;i>1;i–){&nbsp//对当前无序区R[1..i]进行堆排序,共做n-1趟。&nbspR[0]=R[1];R[1]=R[i];R[i]=R[0];&nbsp//将堆顶和堆中最后一个记录交换&nbspHeapify(R,1,i-1);&nbsp//将R[1..i-1]重新调整为堆,仅有R[1]可能违反堆性质&nbsp}&nbsp//endfor&nbsp}&nbsp//HeapSort(4)&nbspBuildHeap和Heapify函数的实现&nbsp因为构造初始堆必须使用到调整堆的操作,先讨论Heapify的实现。&nbsp1、Heapify函数思想方法&nbsp每趟排序开始前R[l..i]是以R[1]为根的堆,在R[1]与R[i]交换后,新的无序区R[1..i-1]中只有R[1]的值发生了变化,故除R[1]可能违反堆性质外,其余任何结点为根的子树均是堆。因此,当被调整区间是R[low..high]时,只须调整以R[low]为根的树即可。&nbsp”筛选法”调整堆&nbspR[low]的左、右子树(若存在)均已是堆,这两棵子树的根R[2low]和R[2low+1]分别是各自子树中关键字最大的结点。若R[low].key不小于这两个孩子结点的关键字,则R[low]未违反堆性质,以R[low]为根的树已是堆,无须调整;否则必须将R[low]和它的两个孩子结点中关键字较大者进行交换,即R[low]与R[large](R[large].key=max(R[2low].key,R[2low+1].key))交换。交换后又可能使结点R[large]违反堆性质,同样由于该结点的两棵子树(若存在)仍然是堆,故可重复上述的调整过程,对以R[large]为根的树进行调整。此过程直至当前被调整的结点已满足堆性质,或者该结点已是叶子为止。上述过程就象过筛子一样,把较小的关键字逐层筛下去,而将较大的关键字逐层选上来。因此,有人将此方法称为”筛选法”。2、BuildHeap的实现&nbsp要将初始文件R[l..n]调整为一个大根堆,就必须将它所对应的完全二叉树中以每一结点为根的子树都调整为堆。&nbsp显然只有一个结点的树是堆,而在完全二叉树中,所有序号大于n/2的结点都是叶子,因此以这些结点为根的子树均已是堆。这样,我们只需依次将以序号为n/2,…,1的结点作为根的子树都调整为堆即可。3.&nbsp用.net写的一个例子,效率不是很高,还是用c写比较好

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Demo.Arithmetic.Sort;
namespace Demo.Arithmetic.DS
{
    /// <summary>
    /// Represents a heap.
    /// </summary>
    /// <typeparam name="T">A comparable data structure.</typeparam>
    public class Heap<T> where T : IComparable
    {
        /// <summary>
        /// Heap type, either big root a small root.
        /// </summary>
        HeapType _heapType = HeapType.BigRoot;
        /// <summary>
        /// An array contains the heap's data.
        /// </summary>
        T[] _rawData;
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="capability">The heap's capability.</param>
        /// <param name="heapType">The heap type.</param>
        public Heap(int capability, HeapType heapType)
        {
            // Initializes the array.
            _rawData = new T[capability];
            _heapType = heapType;
        }
        #region Public methods
        /// <summary>
        /// Sorts the array.
        /// </summary>
        /// <param name="sortOrder">Sort order.</param>
        public void Sort(SortOrder sortOrder)
        {
            if (sortOrder == SortOrder.None) return;
            if (_rawData == null || _rawData.Length <= 1) return;
            HeapType formerHeapType = _heapType;
            // If the order is ascending, then use big root, otherwise use small root.
            _heapType = sortOrder == SortOrder.Ascending ? HeapType.BigRoot : HeapType.SmallRoot;
            // Build the heap up.
            BuildHeap();
            for (int i = _rawData.Length - 1; i > 0; i--)
            {
                Exchange(0, i);
                Heapify(0, i - 1);
            }
            _heapType = formerHeapType;
        }
        /// <summary>
        /// Build the heap up.
        /// </summary>
        public void BuildHeap()
        {
            for (int i = _rawData.Length / 2 - 1; i >= 0; i--)
            {
                Heapify(i, _rawData.Length - 1);
            }
        }
        public void Heapify(int rootIndex, int lastIndex)
        {
            // If the root node is a leaf, then it is a heap already.
            if (IsLeaf(rootIndex, lastIndex)) return;
            int nextRootIndex = GetRootIndex(rootIndex, lastIndex);
            if (nextRootIndex == rootIndex)
            {
                return;
            }
            else
            {
                // Exchange.
                Exchange(rootIndex, nextRootIndex);
                // Verify the heap.
                Heapify(nextRootIndex, lastIndex);
            }
        }
        #endregion
        #region Private methods
        /// <summary>
        /// Returns the root's index by compare the parent node and children nodes according to the heap's type.
        /// </summary>
        /// <param name="rootIndex">The parent's node index.</param>
        /// <param name="lastIndex">The heap's last index.</param>
        /// <returns>The root's index.</returns>
        private int GetRootIndex(int rootIndex, int lastIndex)
        {
            int tLeftIndex = rootIndex + rootIndex + 1;
            if (tLeftIndex > lastIndex) return rootIndex;
            int nextRootIndex = ((_heapType == HeapType.BigRoot && _rawData[rootIndex].CompareTo(_rawData[tLeftIndex]) > 0) ||
                (_heapType == HeapType.SmallRoot && _rawData[rootIndex].CompareTo(_rawData[tLeftIndex]) < 0)) ?
                rootIndex : tLeftIndex;
            int tRightIndex = rootIndex + rootIndex + 2;
            if (tRightIndex > lastIndex) return nextRootIndex;
            nextRootIndex = ((_heapType == HeapType.BigRoot && _rawData[nextRootIndex].CompareTo(_rawData[tRightIndex]) > 0) ||
                (_heapType == HeapType.SmallRoot && _rawData[nextRootIndex].CompareTo(_rawData[tRightIndex]) < 0)) ?
                nextRootIndex : tRightIndex;
            return nextRootIndex;
        }
        /// <summary>
        /// Exchanges the nodes.
        /// </summary>
        /// <param name="firstIndex">The first node's index.</param>
        /// <param name="secondIndex">The second node's index.</param>
        private void Exchange(int firstIndex, int secondIndex)
        {
            T temp = _rawData[firstIndex];
            _rawData[firstIndex] = _rawData[secondIndex];
            _rawData[secondIndex] = temp;
        }
        #endregion
        #region Static methods
        /// <summary>
        /// Checks if the node is a leaf.
        /// </summary>
        /// <param name="nodeIndex">The node's index.</param>
        /// <param name="lastIndex">The last index of the heap.</param>
        /// <returns>Returns true if the node is a leaf.</returns>
        private static bool IsLeaf(int nodeIndex, int lastIndex)
        {
            return nodeIndex + nodeIndex + 1 > lastIndex;
        }
        #endregion
        #region Properties
        public T this[int i]
        {
            get
            {
                return _rawData[i];
            }
            set
            {
                _rawData[i] = value;
            }
        }
        /// <summary>
        /// The capability.
        /// </summary>
        public int Capability
        {
            get
            {
                return _rawData.Length;
            }
        }
        #endregion
    }
    /// <summary>
    /// Heap type.
    /// </summary>
    public enum HeapType
    { 
        BigRoot = 0x00,
        SmallRoot = 0x01
    }
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C# 实现堆排序算法代码
喜欢 (0)
加载中……