导航

C# 堆排序 完整代码

Posted on 2009-07-04 11:30  kingwangzhen  阅读(970)  评论(2编辑  收藏  举报

using System;
using System.Collections.Generic;
using System.Text;

namespace MaxHeapSort
{
    class Program
    {
        private static int[] myArray;
        private static int arraySize;

        //交换数据
        static void Exchange(int i,int j)
        {
            int temp;
            temp = myArray[i];
            myArray[i] = myArray[j];
            myArray[j] = temp;
        }
        //利用向下遍历节点建立堆
        static void TraversingHeap(int vNode)
        {
            int wNode = 2*vNode + 1; //节点wNode是vNode的第一个子节点
            while(wNode<arraySize)
            {
                //如果vNode 有第二个子节点,将wNode设置成vNode下面最大的子节点
                if (wNode + 1 < arraySize)
                    if (myArray[wNode + 1] > myArray[wNode])
                        wNode++;
                //如果vNode已经是最大,则返回
                if(myArray[vNode]>myArray[wNode])
                    return;

                //如果vNode不是,交换vNode和wNode值
                Exchange(vNode,wNode);

                //继续查找下一个节点
                vNode = wNode;
                wNode = 2*wNode + 1;
            }
        }
        //建立Heap
        static void Buildheap()
        {
            for(int vNode=arraySize/2-1;vNode>=0;vNode--)
               TraversingHeap(vNode);
        }
        static void HeapSort()
        {
            Buildheap();
            while(arraySize>1)
            {
                arraySize--;
                Exchange(0,arraySize);
               TraversingHeap(0);
            }
        }
        static void Main(string[] args)
        {
            int[] a = {42, 13, 24, 91, 23, 16, 05, 88};

            myArray = a;
            arraySize = a.Length;
            HeapSort();

            for(int i=0;i<a.Length;i++)
                Console.Write(a[i]+" ");

            Console.Read();
        }
    }
}