您的位置:首页 > 产品设计 > UI/UE

堆排序(Heap Sort)算法的实现

2010-07-17 02:07 513 查看
堆排序算法思想非常简单,先把一个数组看成一个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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 build class