堆排序的java实现

来源:互联网 发布:电脑自带编程软件在哪 编辑:程序博客网 时间:2024/05/16 01:10

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);}}}


原创粉丝点击