1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| import java.util.Arrays;
public class SmallHeap {
public static int[] topN(int[] arr, int n) {
int[] list = new int[n]; System.arraycopy(arr, 0, list, 0, n); for (int i = 0; i < n; i++) { int t = i; while (t != 0 && list[parent(t)] > list[t]) { swap(list, t, t = parent(t)); } }
for (int i = n, len = arr.length; i < len; i++) { if (arr[i] >= list[0]) { list[0] = arr[i]; int t = 0; while ((left(t) < n && list[t] > list[left(t)]) || (right(t) < n && list[t] > list[right(t)])) { if (right(t) < n && list[right(t)] < list[left(t)]) { swap(list, t, t = right(t)); } else { swap(list, t, t = left(t)); } } } } return list; }
private static void swap(int[] list, int i, int j) { int tmp = list[i]; list[i] = list[j]; list[j] = tmp; }
private static int parent(int i) { return (i - 1) / 2; }
private static int left(int i) { return 2 * i + 1; }
private static int right(int i) { return 2 * i + 2; } public static void main(String[] args) { int[] arr = new int[]{56, 30, 71, 18, 29, 93, 44, 75, 20, 65, 68, 34}; System.out.println("原始数组: "); System.out.println(Arrays.toString(arr)); System.out.println("调整后数组: "); System.out.println(Arrays.toString(SmallHeap.topN(arr, 5))); } }
|