import java.util.Arrays; public class Main { public static void main(String[] args) { int[] a = {20,6,3,6,1,3,5,6,7,-1,-4,-9}; heapSort(a); System.out.println(Arrays.toString(a)); } public static void heapSort(int[] a){ int left = 0; int right = a.length-1; for(int i=0;i<a.length;i++){ heapMax(a,left,right); int temp = a[0]; a[0] = a[a.length-1-i]; a[a.length-1-i] = temp; right--; } } //建立大顶堆 public static void heapMax(int[] a,int left,int right){ for(int i = (right-left)/2;i>=0;i--){ if(2*i+2<=right&&a[2*i+2]>a[i]){ int temp = a[2*i+2]; a[2*i+2] = a[i]; a[i] = temp; } if(2*i+1<=right&&a[2*i+1]>a[i]){ int temp = a[2*i+1]; a[2*i+1] = a[i]; a[i] = temp; } } } }
堆排序过程
最新推荐文章于 2024-09-04 21:39:45 发布