import java.util.Arrays;
public class Test_02 {
public static void main(String[] args) {
int[] arr = { 27, 46, 12, 33, 49, 27, 36, 40, 42, 50, 51 };
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void heapSort(int[] arr) {
for(int i=arr.length/2-1; i>=0; i--) {
heapify(arr, arr.length-1, i);
}
for(int i=arr.length-1;i>0;i--) {
swap(arr,0,i);
heapify(arr, i-1, 0);
}
}
public static void heapify(int[] arr,int n,int i) {
int largest = i;
int lson = i*2+1;
int rson = i*2+2;
if(lson<n && arr[largest]<arr[lson]) {
largest = lson;
}
if(lson<n && arr[largest]<arr[rson]) {
largest = rson;
}
if(largest!=i) {
swap(arr,largest,i);
heapify(arr, n, largest);
}
}
public static void swap(int[] arr,int i,int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
排序算法:堆排序(Java实现)
最新推荐文章于 2024-11-01 17:03:26 发布