public static int[] heapSort(int[] arr) {
if (arr == null || arr.length < 2) {
return null;
}
for (int i = 0; i < arr.length; i++) {
heapInsert(arr, i);
}
int heapSize = arr.length;
swap(arr, 0, --heapSize);//先和大根堆最后一数交换,堆的长度减一
while (heapSize > 0) {
heapify(arr, 0, heapSize);//调整
swap(arr, 0, --heapSize);//再和大根堆最后一个数交换,堆的长度减一
}
return arr;
}
//建立大根堆
public static void heapInsert(int []arr,int index) {
while(arr[index]>arr[(index-1)/2]) {
swap(arr,index,(index-1)/2);
index=(index-1)/2;
}
}
//大根堆调整
public static void heapify(int []arr,int index,int heapSize) {
int left=index*2+1;
while(left<heapSize) {
int largest=left+1< heapSize && arr[left+1]>arr[left] ? left+1:left;
largest=arr[index]>arr[largest] ?index:largest;
if(largest==index) {
break;
}
swap(arr,index,largest);
index=largest;//交换位置,数也要交换
left=index*2+1;
}
}
public static void swap(int arr[] ,int i,int j) {
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String[] args) {
int arr[]= {4,5,1,6,2,7,3,8};//12345678
int[] heapSort = heapSort(arr);
for (int i : heapSort) {
System.out.println(i);
}
}