用数组表示大根堆
package bin2;
import java.util.Arrays;
//用数组表示大根堆
public class TestSortDemo {
//向下调整
//时间复杂度:log2^n
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 temp = array[child];
array[child] = array[parent];
array[parent] = temp;
parent = child;
child = 2 * parent + 1;
} else {
break;
}
}
}
//此时已经是一个大根堆
//时间复杂度:(n/2) * log2^n
public static void createHeap(int[] array){
for (int i = (array.length-1-1)/2; i >=0 ; i--) {
adjustDown(array,i,array.length);
}
}
//将大根堆从小到大排序
public static void heapSort(int[] array){
createHeap(array);//首先要是一个大根堆
int end=array.length-1;
//将末尾结点与0号位结点交换,调整,一直到end调整到0结点
while (end>0){
int temp=array[end];
array[end]=array[0];
array[0]=temp;
adjustDown(array,0,end);
end--;
}
}
public static void main(String[] args) {
int[] array={27,15,19,18,28,34,65,49,25,37};
System.out.println(Arrays.toString(array));
heapSort(array);
System.out.println(Arrays.toString(array));
}
}