package com.fsw.demo.heap;
import java.util.*;
/**
* Created by fanshuwen on 2020/06/03
*/
public class MinHeap {
public static void main(String[] args) {
Integer [] arr={0,4,2,6,5,7,1,3,8,9};
List list = Arrays.asList(arr);
initHeap(list);
System.out.println(list);
}
public static void initHeap(List list){
//在第一个位置添加一个东西 好计算
adjust(list.size()-1,list,(list.size()-1)/2);
}
public static void adjust(int size,List list,int index){
if(index>=size||index==0){
return;
}
Integer parent = list.get(index);
int left = left(index);
int right = right(index);
if(left>size){
return;
}
Integer leftVal = list.get(left);
if(leftValsize||list.get(right)>=leftVal)){
//左边最小 交换左边与父节点数据
Collections.swap(list,index,left);
adjust(size,list,left);
}else if(right<=size&&leftVal>list.get(right)&&list.get(right)
//右边小
Collections.swap(list,index,right);
adjust(size,list,right);
}
//当前节点不需要调整
adjust(size,list,index-1);
}
public static int left(int index){
return index*2;
}
public static int right(int index){
return index*2+1;
}
}
一键复制
编辑
Web IDE
原始数据
按行查看
历史