简述:(以max-heap为例)堆是一个完全二叉树,根结点值最大,父节点的值高于所有子节点。新值插入末尾子节点,此节点不断地和父值对比,大于父值则交换位置。
二叉树:当前节点下标为i,左子节点为2i+1,右子节点为2i+2
时间复杂度:O(nlogn)
理解:logn为树的深度,n为数组长度
import java.util.Arrays;
public class heapsort {
public static void main(String[] args){
int[] ori_array= {3,4,5,6,1,7,8};
int[] result = new int[ori_array.length];
result[0] = ori_array[0];
for (int i=1; i<ori_array.length; i++){
int father_pos = i;
int new_value_pos_record;
do{
new_value_pos_record = father_pos;//记录new value位置,这里默认需要交换,新值当前位置=上一次父节点位置。
father_pos = (father_pos-1)/2; // 因为new value要不断地与当前的父值比较,所以父节点的位置要不断更新
// System.out.println("父节点位置:"+father_pos+","+"父值:"+result[father_pos]);
// System.out.println("新节点位置:"+new_value_pos_record+","+"新值:"+ori_array[i]);
if (result[father_pos] < ori_array[i]) { //如果父值小于新值,交换位置
int temp = ori_array[i];
result[new_value_pos_record] = result[father_pos];
result[father_pos] = temp;
// System.out.println(Arrays.toString(result));
}else{ //如果父值大于新值
result[i] = ori_array[i];
}
}while(father_pos != 0);
System.out.println(Arrays.toString(result));
}
}
}