Quick line idea, select the sequence of a key to divide, less than key on the left, greater than the key on the right, the position of key-low+1 is the last element is the number of elements in the sequence of key, when the number of elements greater than k, in the left half of the recursive search, equal to Arr[key] is the K
Large element, less than K, recursively finding the K-num large element on the right
/** * File name: Findk.java * Time: November 7, 2014 11:23:43 * Xiu Kang */package chapter7;/** * class Name: FINDK Description: Found an array of K-Large elements */public class Fin DK {public static int partition (int[] A, int. low, int.) {int key = A[low];while (Low < High) {when (Low < high && A[high] >= key) High--;a[low] = A[high];while (Low < high && A[low] <= key) Low++;a[high] = A[lo W];} A[low] = Key;return low;} public static int Quickselect (int[] A, int. low, Int. High, Int. K) {if (low = = high) return a[low];int Keypos = partition (A, Low, high); int num = Keypos-low + 1;if (num = = k) return A[keypos];else if (K < num) return Quickselect (A, low, keypos -1, k); Elsereturn Quickselect (A, Keypos + 1, high, k-num);} /** * Method Name: Main Description: Test */public static void Main (string[] args) {//TODO auto-generated method stubint[] A = new int[] {1, 2, 3,4,5,6,7,8,9,10}; System.out.println (Quickselect (A, 0, a.length-1,5));}}
Find the number of K in an array