基本排序算法之堆排序

基础知识

1991年计算机先驱奖获得者、斯坦福大学计算机科学系教授罗伯特·弗洛伊德(Robert W.Floyd)和威廉姆斯(J.Williams)在1964年共同发明了著名的堆排序算法(Heap Sort )。(二叉)堆数据结构是一种数据对象,它可以被视为一棵完全二叉树,树中每个节点与数组中存放该节点的那个元素对应,树的每一层都是填满的,最后一层可能除外(最后一层从最左边节点的左子树开始填。堆氛围两种:最大堆(大根堆)和最小堆(小跟堆)。一个最大堆可以看成一棵完全二叉树和一个数组(见图一),圆圈中的数字表示书中每个节点存储的值,及诶单那上方的数字表示对应的数组下标。图一中树的高度为小堆的组织方式与最大堆恰好相仿。使得在当前无序区中选取最大(或最小)关键字的记录变得简单。

图一

算法理解

算法主要分为两个过程:建堆和堆排序。图二是建堆过程,图三是堆排序过程。

图二

 

 

图三

 

Java代码

 1 package chap06;
 2 
 3 public class HeapSort {
 4 
 5     private int[] waitForSortedArray;
 6     private int heapSize;
 7 
 8     public HeapSort(int[] IntArray) {
 9         this.waitForSortedArray = IntArray;
10         this.heapSize = this.waitForSortedArray.length - 1;
11     }
12 
13     /* return left child index */
14     public int getLeftChild(int parentIndex) {
15         return parentIndex * 2 + 1;
16     }
17 
18     /* return right child index */
19     public int getRightChild(int parentIndex) {
20         return parentIndex * 2 + 2;
21     }
22 
23     /* exchange two number in Array */
24     public void swap(int array[], int index1, int index2) {
25         int tempNum = 0;
26         tempNum = array[index1];
27         array[index1] = array[index2];
28         array[index2] = tempNum;
29     }
30     
31     /* output the result of array sorted */
32     public void outputSortedResult() {
33         for(int i = 0;i < waitForSortedArray.length ; i++){
34             System.out.println(waitForSortedArray[i]);
35         }
36     }
37     
38     /* Adjust the heap to meet the max heap property */
39     public void MAX_HEAPIFY(int[] A, int index) {
40         int lIndex = getLeftChild(index);
41         int rIndex = getRightChild(index);
42         int largest = 0;
43         if (lIndex <= heapSize && A[lIndex] > A[index]) {
44             largest = lIndex;
45         } else {
46             largest = index;
47         }
48         if (rIndex <= heapSize && A[rIndex] > A[largest]) {
49             largest = rIndex;
50         }
51 
52         if (largest != index) {
53             swap(A, largest, index);
54             MAX_HEAPIFY(A, largest);
55         }
56     }
57 
58     /* build heap */
59     public void BUILD_MAX_HEAP(int[] A) {
60         int tmp = heapSize / 2;
61         for (int i = tmp; i >= 0; i--) {
62             MAX_HEAPIFY(A, i);
63         }
64     }
65 
66     /* heap sort */
67     public void HEAPSORT(int[] A) {
68 
69         BUILD_MAX_HEAP(A);
70         for (int i = heapSize; i >= 1; i--) {
71             swap(A, 0, i);
72             heapSize = heapSize - 1;
73             MAX_HEAPIFY(A, 0);
74         }
75     }
76 
77     public static void main(String[] args) {
78          int [] array = {5,3,1,7,9,11, 13, 2};
79          HeapSort test = new HeapSort(array);
80          test.HEAPSORT(array);
81          test.outputSortedResult();
82     }
83 }
原文地址:https://www.cnblogs.com/RobertC/p/3431635.html