//构建大顶堆,依次取出堆顶值(最大值),即可有序排列 //该算法需要一个顶堆数据结构 和一个有序数组 //排列的结果会更改相同值的相对顺序 class HeapSort1 { public static void main(String[] args) { int[] heap=createHeap(new int[]{5, 2, 7, 3, 6, 1, 4}); int[] sorted=new int[heap.length]; for(int index=0;index<heap.length;index++) { sorted[heap.length-index-1]= popElement(heap,index); } println(sorted); } private static void println(int[] arr) { for (int i : arr) { System.out.print(" "+i); } System.out.println(); } private static int[] createHeap(int[] randomArray) { int[] heap=new int[randomArray.length]; for(int index=0;index<randomArray.length;index++) { addElement(heap,index-1,randomArray[index]); } return heap; } private static void addElement(int[] src,int lastIndex,int element) { src[++lastIndex]=element; int parentIndex=lastIndex; int currentIndex=lastIndex; while (currentIndex>0) { parentIndex=(lastIndex-1)/2; int parentValue=src[parentIndex]; //大的向上冒泡 if(element>parentValue) { src[parentIndex]=element; src[currentIndex]=parentValue; currentIndex=parentIndex; }else break; } } private static int popElement(int [] src,int poppedCount) { int ele=src[0]; //为了节省空间,没有每次new一个新数组 int lastIndex=src.length-poppedCount-1; //尾结点替换堆顶 src[0]=src[lastIndex]; poppedCount++; //堆顶下沉 int childIndex=0; int currentIndex=0; while (currentIndex<=lastIndex) { int childIndexLeft=currentIndex*2+1; if(childIndexLeft>=lastIndex) break; int childIndexRight=currentIndex*2+2; int childLeftValue=src[childIndexLeft]; int childRightValue=childIndexRight>lastIndex?-1:src[childIndexRight]; int parentValue=src[currentIndex]; //下沉 if(parentValue!=Math.max(Math.max(parentValue,childLeftValue),childRightValue)) { int desChildIndex=childLeftValue>=childRightValue?childIndexLeft:childIndexRight; int desChildValue=childLeftValue>=childRightValue?childLeftValue:childRightValue; src[desChildIndex] = parentValue; src[currentIndex] = desChildValue; currentIndex = desChildIndex; } else break; } return ele; } }
堆排序(1)
最新推荐文章于 2024-11-16 10:02:08 发布