首页 > c#, 数据结构与算法 > 输入10个数字,应用堆排序算法用c#实现

输入10个数字,应用堆排序算法用c#实现

请用c#写出一个堆排序算法,要求输入10个整数,输出排序结果。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HeapSorter
{
class Program
{
private static int[] myArray;
private static int arraySize;
public static void Sort(int[] a)
{
myArray = a;
arraySize = myArray.Length;
HeapSort();
}
private static void HeapSort()
{
BuildHeap();//将原始序列建成一个堆
while (arraySize > 1)
{
arraySize--;
Exchange(0, arraySize);//将最大值放在数组的最后
TraversingHeap(0);//将序列从0到n-1看成一个新的序列,重新建立堆
}
}
//互换数据
private static void Exchange(int i,int j)
{
int t = myArray[i];
myArray[i] = myArray[j];
myArray[j] = t;
}
private static void BuildHeap()
{
for (int vNode = arraySize / 2 - 1; vNode >= 0; vNode--)
{
TraversingHeap(vNode);
}
}
//利用向下遍历子结点建立堆
private static void TraversingHeap(int vNode)
{
int wNode = 2 * vNode + 1;//结点w是结点vNode的第一个子结点
while (wNode < arraySize)
{
if (wNode + 1 < arraySize)//如果结点vNode下面有第二个字结点
if (myArray[wNode + 1] < myArray[wNode])
wNode++;//将子结点wNode设置成结点vNode下面值最大的子结点

if (myArray[vNode] >= myArray[wNode])//结点vNode已经大于子结点wNode,则返回
return;
Exchange(vNode, wNode);//如果不是,就交换结点vNode和wNode的值
vNode = wNode;
wNode = 2 * vNode + 1;//继续向下找子节点
}
}

static void Main(string[] args)
{
int[] a = new int[] { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
Program.Sort(a);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
}
}
}

原创文章转载请注明出处:云飞扬IT的blog

本文链接: http://www.ajaxcn.net/archives/287

分类: c#, 数据结构与算法 标签: ,
一键分享到:新浪微博分享  分享到网易微博    转贴到开心网  推荐到豆瓣  分享到QQ空间    RSS订阅
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.