import java.util.Arrays;
public class HeapSort {
public static void main(String[] args) {
int[] nums = new int[]{5,2,6,8,4,3,1,10,52,692,23,1616,23,54};
HeapSort heapSort = new HeapSort();
heapSort.heapSort(nums,0,nums.length-1);
System.out.println(Arrays.toString(nums));
}
public void heapSort(int[] nums,int head,int tail){
heapBuild(nums,tail);
for (int i=tail;i>=head;i--){
swap(nums,i,head);
heapF(nums,i-1,head);
}
}
public void heapBuild(int[] nums,int tail){
int fa = (tail-1)/2;
for (int i=fa;i>=0;i--){
heapF(nums,tail,i);
}
}
public void heapF(int[] nums,int tail,int n){
if (tail < n) return;
int left = 2*n+1;
int right = 2*n+2;
int max = n;
if (left<=tail&&nums[left]<nums[max]){
max = left;
}
if (right<=tail&&nums[right]<nums[max]){
max = right;
}
if (max != n){
swap(nums,max,n);
heapF(nums,tail,max);
}
}
public void swap(int[] nums,int l,int r){
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
}
}