实现思路:
代码实现:
import java.util.Arrays;
/**
* @Author: PurcellHuang
* @Date: 2019-08-09 16:44
*/
public class HeapSort {
/**
* @Author: PurcellHuang
* @Date: 2019-08-09 16:49
* 堆排序
*/
public static void sort(int []arr){
int start = (arr.length-1)/2;
for (int i = start ; i >= 0; i--){
maxHeap(arr,arr.length,i);
}
for (int i = arr.length-1; i > 0;i--){
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
maxHeap(arr,i,0);
}
}
/**
* @Author: PurcellHuang
* @Date: 2019-08-09 16:49
* 建立大顶堆
*/
public static void maxHeap(int []arr, int size, int index){
int leftNode = 2*index+1;
int rightNode = 2*index+2;
int max = index;
if (leftNode < size && arr[leftNode] > arr[max]){
max = leftNode;
}
if (rightNode < size && arr[rightNode] > arr[max]){
max = rightNode;
}
if (max != index){
int temp = arr[index];
arr[index] = arr[max];
arr[max] = temp;
maxHeap(arr,size,max);
}
}
public static void main(String[] args) {
int []a = {2,4,5,2,1,88,8,9,21,2,5};
HeapSort.sort(a);
System.out.println(Arrays.toString(a));
}
}