堆分为最大堆和最小堆,是对数组的完全二叉树的表示方式。
import java.util.ArrayList;
public class heapsort {
static ArrayList<Integer> res = new ArrayList<>();
public static void main(String[] args) {
int [] ints = new int[]{3,2,4,1,5,8,6,7,10,15,14,12,13};
heapSort(ints, ints.length);
for(Integer ss:res){
System.out.println(ss);
}
}
static void heapSort(int [] input, int k){
for(int i=(input.length-1)/2;i>=0;i--){
heapfy(input, i, input.length);
}
for(int i=input.length-1;i>=0&&k>=0;i--,k--){
res.add(input[0]);
int temp = input[i];
input[i] = input[0];
input[0] = temp;
heapfy(input, 0, i);
}
}
static void heapfy(int [] input, int parent, int length){
int temp = input[parent];
int lChild = 2*parent+1;
while(lChild<length){
int rChild = lChild+1;
if(rChild<length&&input[rChild]>input[lChild]) lChild++;
if(temp>input[lChild])break; //这里需要注意,temp是parent位置值,等到最终确定parent位置时再赋值
input[parent] = input[lChild];
parent = lChild;
lChild = 2*lChild+1;
}
input[parent]=temp;
}
}