当前位置: 代码迷 >> 综合 >> JAVA 排序:堆排序。
  详细解决方案

JAVA 排序:堆排序。

热度:38   发布时间:2024-02-07 14:13:49.0
public static void creatHeap(int[] array) {          //建堆;for (int i =(array.length-1-1)/2; i >= 0 ; i--) {adjustDown(array,i,array.length);}
}
public static void adjustDown(int[] array,int root,int len) {    //向下调整;int parent = root;int child = 2*parent+1;while (child < len) {if (child+1 < len && array[child] < array[child+1]) {child++;}if (array[child] > array[parent]) {int tmp = array[child];array[child] = array[parent];array[parent] = tmp;parent = child;child = 2*parent+1;} else {break;}}
}
public static void heapSort(int[] array) {  //堆排序;creatHeap(array);int end = array.length-1;while (end > 0) {int tmp = array[0];array[0] = array[end];array[end] = tmp;adjustDown(array, 0, end);end--;}
}

基本原理也是选择排序,只是不在使用遍历的方式查找无序区间的最大的数,而是通过堆来选择无序区间的最大的
数。

注意: 排升序要建大堆;排降序要建小堆。

时间复杂度 :              O(n * log(n))          数据不敏感

空间复杂度 :              O(1)                       数据不敏感 

稳定性:  不稳定。