少壮不努力,老大徒伤悲
堆排序算法的复杂度与归并排序算法一样,都是logn,但是堆排序算法的优点在于无需使用额外的存储空间。
要使用堆排序算法,有几个概念是需要清楚的:
二叉堆:有数组构成的堆,可以被看成一个近似的完全二叉树。
最大堆:每个节点的值都小于等于其父节点。
还有几个结论应当知道:
对于下标为i的节点,其父节点下标为i/2,左右子节点下标分别为2i和2i+1;(这里及下文的描述中的下标均是从1开始)
对于有n个元素的数组形成的二叉堆,叶子节点为[n/2]+1, [n/2]+2 ... n;(这里的[ ]代表向下取整)
最后,进行堆排序算法的主要步骤如下:
1. 输入数组为A,下标i,对以i为根节点的子树进行排序,找出i及其左右叶子节点中的最大值,形成一个最大堆
2. 通过1中的方法进行递归,将整个输入数组构造成一个最大堆。这里需要注意的是,只需要递归全部根节点即可,因为[n/2]+1, [n/2]+2 ... n全部为叶子节点,故无需处理。
3. 最大堆中,最大的值为根节点,将根节点与下标为n的叶子节点对调,这样最大值就变成了下标为n的节点,此时将最大值从堆中移出,即认为数组的最大下标为n-1,重新构建最大堆。
4. 递归重复以上操作,每次都将最大堆的根节点放在最后一个下标出,最后形成一个升序的数组。
注意,在代码中,数组的下标是以0开始的!因此要注意实现时与算法描述的不同之处!
C++代码实现示例:
int nHeapSize = 0;
extern void MaxHeapSort(int* A, int length);
int main()
{
int A[] = {23, 17, 14, 6, 13, 10, 1, 5, 7, 12};
MaxHeapSort(A, 10);
system("pause");
return 0;
}
void MaxHeap(int* A, int i)
{<pre class="cpp" name="code"> // Note the first index of array is 0.
int iLeft = 2 * i + 1;
int iRight = 2 * i + 2;
int largest = i;
if (iLeft < nHeapSize && A[iLeft] > A[i])
{
largest = iLeft;
}
if (iRight < nHeapSize && A[iRight] > A[largest])
{
largest = iRight;
}
if (i != largest)
{
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
}
}
void BuildMaxHeap(int* A, int length)
{
nHeapSize = length;
// Generate max-heap from all parent nodes. Generate the max-heap from bottom nodes to the top.
for (int i = length / 2 - 1; i >= 0; i--)
{
MaxHeap(A, i);
}
}
void MaxHeapSort(int* A, int length)
{
if (length == 0)
{
return;
}
BuildMaxHeap(A, length);
// Move the root node to the last
int temp = A[0];
A[0] = A[nHeapSize - 1];
A[nHeapSize - 1] = temp;
MaxHeapSort(A, length - 1);
}
Java代码实现示例:
public static int heapSize = 0;
public static void main(String[] args) {
int A[] = { 23, 17, 14, 6, 13, 10, 1, 5, 7, 12 };
heapSize = A.length;
maxHeapSort(A);
for (int i : A) {
System.out.println(i);
}
}
public static void maxHeap(int[] A, int index) {
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
int largest = index;
if (leftIndex < heapSize && A[leftIndex] > A[index]) {
largest = leftIndex;
}
if (rightIndex < heapSize && A[rightIndex] > A[largest]) {
largest = rightIndex;
}
if (largest != index) {
int temp = A[index];
A[index] = A[largest];
A[largest] = temp;
}
}
public static void buildMaxHeap(int[] A) {
for (int i = heapSize / 2 - 1; i >= 0; i--) {
maxHeap(A, i);
}
}
public static void maxHeapSort(int[] A) {
if (heapSize == 0) {
return;
}
buildMaxHeap(A);
int temp = A[0];
A[0] = A[heapSize - 1];
A[heapSize - 1] = temp;
heapSize--;
maxHeapSort(A);
}