> 文档中心 > 堆排序的代码实现(java语言实现)

堆排序的代码实现(java语言实现)


实现代码

public class Heap {public static void main(String[] args) {//调整堆测试int arr[] = {1,0,3,2,6,5,4,9};//调整堆for(int i=arr.length/2-1;i>=0;i--) {adjust(arr,i,arr.length-1);}//调整堆结果System.out.println("调整堆结果");for(int i=0;i<arr.length;i++) {System.out.print(arr[i]+" ");}//排序测试System.out.println();int heapArr[] = {1,0,7,3,8,2,10,6,5,4,9};//排序sort(heapArr,heapArr.length-1);//排序结果System.out.println("排序结果");for(int i=0;i<heapArr.length;i++) {System.out.print(heapArr[i]+" ");}}/** * 调整一颗满二叉树部分调整为最大顶堆 * @param heapArr 按照层级遍历 用数组存储的一颗满二叉树 * @param fatherNode 树顶节点索引 * @param endIndex 待调整部分的最后一个节点的索引 */public static void adjust(int heapArr[],int fatherNode,int endIndex) {int temp;if(fatherNode*2+1>endIndex)return;if(fatherNode*2+1==endIndex) {if(heapArr[fatherNode*2+1]>heapArr[fatherNode]) {temp = heapArr[fatherNode];heapArr[fatherNode] = heapArr[fatherNode*2+1];heapArr[fatherNode*2+1] = temp;}return;}if(fatherNode*2+1<endIndex) {if(heapArr[fatherNode*2+1]>heapArr[fatherNode]) {temp = heapArr[fatherNode];heapArr[fatherNode] = heapArr[fatherNode*2+1];heapArr[fatherNode*2+1] = temp;}if(heapArr[fatherNode*2+2]>heapArr[fatherNode]) {temp = heapArr[fatherNode];heapArr[fatherNode] = heapArr[fatherNode*2+2];heapArr[fatherNode*2+2] = temp;}adjust(heapArr, fatherNode*2+1, endIndex);adjust(heapArr, fatherNode*2+2, endIndex);}}/** * 排序 * @param heapArr  按照层级遍历 用数组存储的一颗满二叉树 * @param endIndex  待排序部分的最后一个节点的索引 */public static void sort(int heapArr[],int endIndex) {if(endIndex<0)return;//调整for(int i=(endIndex+1)/2-1;i>=0;i--) {adjust(heapArr,i,endIndex);}int temp;temp = heapArr[0];heapArr[0] = heapArr[endIndex];heapArr[endIndex] = temp;sort(heapArr, endIndex-1);}}

测试结果

在这里插入图片描述