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
| public class FindTopK2 { public static void main(String[] args) { int[] arr = new int[]{3, 2, 1, 5 ,6 ,4}; System.out.println(quickSort(arr, 0, arr.length - 1, 1)); System.out.println(quickSort(arr, 0, arr.length - 1, 2)); System.out.println(quickSort(arr, 0, arr.length - 1, 3)); System.out.println(quickSort(arr, 0, arr.length - 1, 4)); System.out.println(quickSort(arr, 0, arr.length - 1, 5)); System.out.println(quickSort(arr, 0, arr.length - 1, 6)); } private static int quickSort(int[] arr, int l, int r, int k){ int idx = l + (int)Math.random() * (r - l + 1); swap(arr, idx, r); int index = partition(arr, l, r); if(index < arr.length - k){ return quickSort(arr, index + 1, r, k); }else if(index > arr.length - k){ return quickSort(arr, l, index - 1, k); }else{ return arr[index]; }
} private static int partition(int[] arr, int l, int r){ int less = l - 1; int more = r; while(l < more){ if(arr[l] < arr[r]){ swap(arr, ++less, l++); }else if(arr[l] > arr[r]){ swap(arr, --more, l); }else{ l++; } } swap(arr, more, r); return more; } private static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
|