堆排序的java实现

本文介绍了一种使用堆数据结构实现的排序算法——堆排序。通过构建最大堆并对数组进行重新组织来达到排序目的。详细展示了堆排序的具体步骤,包括最大堆的建立、堆调整过程以及完整的排序流程。

public class TreeUtils {
public static int getLeftSubNodeIndex(int current){
return 2*current;
}
public static int getRightSubNodeIndex(int current){
return 2*current+1;
}
public static int getParentNodeIndex(int current){
return Integer.parseInt(Double.toString(Math.floor(current/2)));
}
}



public class HeapSorter {

public void sort(int[] needSortArray){
if (needSortArray != null && needSortArray.length > 0){
int heapSize = needSortArray.length;
buildMaxHeap(needSortArray);
for (int i = heapSize -1; i > 0;i--){
int temp = needSortArray[0];
needSortArray[0] = needSortArray[i];
needSortArray[i] = temp;
maxHeapify(needSortArray,0,i);
}
}
}

public void buildMaxHeap(int[] array){
int heapSize = array.length;
for (int i = (heapSize - 1 )/2;i>=0;i--){
maxHeapify(array,i,heapSize);
}
}

public void maxHeapify(int[] array,int currentIndex,int heapSize){
int leftIndex = TreeUtils.getLeftSubNodeIndex(currentIndex);
int rightIndex = TreeUtils.getRightSubNodeIndex(currentIndex);
int maxIndex = currentIndex;
if (leftIndex < heapSize && array[leftIndex] > array[currentIndex]){
maxIndex = leftIndex;
}
if (rightIndex < heapSize && array[rightIndex] > array[maxIndex]){
maxIndex = rightIndex;
}
if (maxIndex != currentIndex){
int tempValue = array[currentIndex];
array[currentIndex] = array[maxIndex];
array[maxIndex] = tempValue;
maxHeapify(array,maxIndex,heapSize);
}
}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值