堆排序算法思想非常简单,先把一个数组看成一个heap, 在下面的实现中,我使用的是max heap, 也就是说根总是比叶子大。所以我们第一步就是建立max heap。建立完毕以后,很明显这个heap的root就是最大的,把最大的根放在数组的最后一个位置,把数组长度缩小一个位置,这样最大的那个数就不会再参与到下次的排序当中,这时,除了根以外,heap的其它部分都保持max heap的特性,所以我们需要再做一次max heap (只对根做),再把最大的放在目前被缩小的数组的最后一个位置,重复下去,知道数组中只剩下一个数。
class HeapSortAlgorithm {
public void HeapSort(int[] array) {
int heapSize = array.length;
for (int i = array.length / 2 - 1; i >= 0; i--) {
MaxHeapify(array, i, array.length);
}
for (int i = array.length - 1; i > 0; i--) {
swap(0, i, array);
heapSize--;
MaxHeapify(array, 0, heapSize);
}
}
/// MaxHeapify is to build the max heap from the 'position'
public void MaxHeapify(int[] array, int position, int heapSize)
{
int left = left(position);
int right = right(position);
int maxPosition = position;
if (left < heapSize && array[left] > array[position]) {
maxPosition = left;
}
if (right < heapSize && array[right] > array[maxPosition]) {
maxPosition = right;
}
if (position != maxPosition) {
swap(position, maxPosition, array);
MaxHeapify(array, maxPosition, heapSize);
}
}
/// return the left child position
public int left(int i)
{
return 2 * i + 1;
}
/// return the right child position
public int right(int i)
{
return 2 * i + 2;
}
}
MaxHeapify的时间复杂度为 O(lgn), 所以整个heap sort的复杂度为:O(n lgn).
转载请注明出处: http://blog.csdn.net/beiyeqingteng