求最小的K个数
public int[] getLeastNumbers(int[] arr, int k) { if(arr.length == 0 || k == 0){ return new int[0]; } //构建小顶堆 buildHeap(arr); //弹出堆顶 重排序 int[] rsp = new int[k]; for(int i = 0; i<k;i++){ rsp[i] = arr[0]; swap(arr,0,arr.length-1-i); execute(arr, 0,arr.length-2-i); } return rsp; } private void buildHeap(int[] arr){ for(int i = arr.length/2-1; i>=0;i--){ execute(arr, i ,arr.length-1); } } private void execute(int[] arr, int head, int right1){ int left = 2*head +1; int right = left +1; int min = head; if(left <= right1 && arr[left]<arr[min]){ min = left; } if(right <= right1 && arr[right]<arr[min]){ min = right; } if(min != head){ swap(arr,head,min); execute(arr, min ,right1); } } private void swap(int[] arr, int head, int min){ int a = arr[head]; arr[head] = arr[min]; arr[min] = a; }
标签:arr,int,堆排序,head,new,left From: https://www.cnblogs.com/jiangym/p/17521231.html