1: #include "stdafx.h"
2: #include
3: #include
4: #include
5:
6: const int HEAP_SIZE = 13; //堆積樹大小
7:
8: void Max_Heapify(int [], int, int);
9: void Build_Max_Heap(int []);
10: void print(int []);
11: void HeapSort(int [], int);
12:
13: /*單一子結點最大堆積樹調整*/
14: void Max_Heapify(int A[], int parent, int heap_size)
15: {
16: int left = 2*parent+1;
17: int right = 2*parent+2;
18: int largest;
19: int temp;
20: if(left < heap_size && A[left] > A[parent])
21: {
22: largest = left;
23: }
24: else
25: {
26: largest = parent;
27: }
28: if(right < heap_size && A[right] > A[largest])
29: {
30: largest = right;
31: }
32: if(largest != parent)
33: {
34: temp = A[parent];
35: A[parent] = A[largest];
36: A[largest] = temp;
37: Max_Heapify(A, largest, heap_size);
38: }
39: }
40:
41: /*建立最大堆積樹*/
42: void Build_Max_Heap(int A[])
43: {
44: for(int i = HEAP_SIZE/2-1; i >= 0; i--)
45: {
46: Max_Heapify(A, i, HEAP_SIZE);
47: }
48: }
49:
50: /*印出樹狀結構*/
51: void print(int A[])
52: {
53: for(int i = 0; i < HEAP_SIZE;i++)
54: {
55: printf("%d ", A[i]);
56: }
57: printf("/n");
58: }
59:
60: /*堆積排序程序碼*/
61: void HeapSort(int A[], int heap_size)
62: {
63: //int temp;
64: Build_Max_Heap(A);
65: for(int i = heap_size - 1; i >= 1; i--)
66: {
67: //temp = A[0];
68: //A[0] = A[i];
69: //A[i] = temp;
70: A[0]^=A[i]^=A[0]^=A[i];
71: //heap_size = heap_size - 1; 其实这里不用更新堆大小
72: Max_Heapify(A, 0, i);
73: }
74: print(A);
75: }
76:
77:
78: int _tmain(int argc, _TCHAR* argv[])
79: {
80: int A[HEAP_SIZE] = {19, 1, 10, 14, 16, 4, 7, 9, 3, 2, 8, 5, 11};
81: HeapSort(A, HEAP_SIZE);
82: system("pause");
83: return 0;
84: }