package org.lion.euler.study.sort;
/**
* 堆排序
*
* 原理:建立大顶堆,交换第一个与最后一个值,重新维护大顶堆。
* @author lion
*
*/
public class HeapSort extends AbstractSort {
@Override
public void sort(Integer[] array) {
int len = array.length/2;
while(len >= 0){
this.heapMax(array, len, array.length);
len -= 1;
}
int curLen = array.length - 1;
while(curLen >= 0){
this.swap(array, 0, curLen);
this.heapMax(array, 0, curLen);
curLen -= 1;
}
}
private void heapMax(Integer[] array, int index, int maxLen){
int len = maxLen;
int curIndex = index;
while(curIndex < len){
int left = curIndex * 2;
int right = left + 1;
int maxIndex = curIndex;
if(left < len && array[left] > array[maxIndex]){
maxIndex = left;
}
if(right < len && array[right] > array[maxIndex]){
maxIndex = right;
}
if(maxIndex > curIndex){
this.swap(array, curIndex, maxIndex);
curIndex = maxIndex;
}else{
break;
}
}
}
}
排序-JAVA实现【四】堆排序
最新推荐文章于 2024-07-14 22:24:20 发布