堆排序的java实现
2012-06-10 20:30
399 查看
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); } } }
相关文章推荐
- java实现堆排序(放入数组的索引对应二叉树节点位置)、归并排序
- 排序算法Java实现——选择排序(堆排序)
- 第6章 堆排序 java实现 简单版 泛型版 最大优先级队列
- 元素排序几种常用的排序算法的分析及java实现(希尔排序,堆排序,归并排序,快速排序,选择排序,插入排序,冒泡排序)
- 几种常用的排序算法的分析及java实现(希尔排序,堆排序,归并排序,快速排序,选择排序,插入排序,冒泡排序)
- java实现堆排序
- java实现算法之堆排序
- java实现堆排序
- 堆排序的java实现
- java递归实现堆排序
- java实现最大堆及堆排序
- java实现最小堆(通过构造函数构造最小堆,相当于堆排序)
- Java实现堆排序
- Java实现堆排序
- 数据结构--排序系列(插入排序,希尔排序,堆排序)Java代码实现
- java实现排序算法之选择排序(简单选择排序和堆排序)
- Java 实现 堆排序 快速排序 以及 TopK问题(二)
- Java实现-高效排序算法之堆排序
- Java实现堆排序
- 堆排序(java实现)