1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4
 5namespace HeapSort
 6{
 7    class Program
 8    {
 9        static void Main(string[] args)
10        {
11            //arr[0]
12            int[] arr = new int[] 0,1,6,2,5,3,432,432,44,3,65,76,879,3,54,54543,33333333,33,2,4};
13            HeapSort sort = new HeapSort(arr);
14            sort.Sort();
15            Console.ReadLine();
16        }

17    }

18
19    class HeapSort
20    {
21        public int[] arr;
22        public int length;
23
24        public HeapSort(int[] arr)
25        {
26            this.arr = arr;
27            this.length = this.arr.Length-1;
28        }

29
30        public void HeapAdjust( int low, int high )
31        {
32            int rc = arr[low];
33
34            for (int i = 2*low; i <= high; i *= 2)
35            {
36                if (i<high && arr[i] < arr[i + 1]) i++;
37                if (arr[i] < rc) break;
38                arr[low] = arr[i]; 
39                low = i; 
40            }

41
42            arr[low] = rc;
43        }

44
45        public void Sort()
46        {
47            for (int i = length / 2; i >= 1; i--)
48            {
49                HeapAdjust(i, length);
50            }

51
52            for (int i = length; i > 1; i--)
53            
54                int temp = arr[1];
55                arr[1= arr[i];
56                arr[i] = temp;
57
58                HeapAdjust(1, i - 1);
59            }

60
61            for (int i = 1; i <= length; i++)
62            {
63                Console.Write(arr[i] + " ");
64            }

65            Console.WriteLine();
66        }

67
68    }

69}

70
posted on 2008-04-22 16:00  shawnliu  阅读(283)  评论(0编辑  收藏  举报