一个快速找第k+1小的算法
public static int randomSelect(int[] A, int k) { return randomSelectDo(A, 0, A.Length - 1, k); } private static int randomSelectDo(int[] A, int low, int high, int k) { int i = randomPartition(A, low, high); //n is the number of < A[i] int n = i - low; if (n > k) return randomSelectDo(A, low, i - 1, k); else if (n == k) return A[i]; else return randomSelectDo(A, i + 1, high, k - n - 1); } private static void swap(int[] A, int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } private static int randomPartition(int[] A, int low, int high) { //random divide Random rand = new Random(); int r = rand.Next(high - low + 1) + low; swap(A, low, r); int i = low; int x = A[low]; for (int j = low + 1; j <= high; j++) { if (A[j] < x) { i++; if (i != j) { swap(A, i, j); } } } swap(A, low, i); return i; } static void Main(string[] args) { int[] I = new int[10]; Random r = new Random(); B: for (int i = 0; i < I.Length; i++) { I[i] = r.Next(20); } foreach (int i in I) { Console.Write(i+" "); } Console.WriteLine("_______________________________________"); int t= randomSelect(I, 0); Console.WriteLine(t); if (Console.ReadLine() == "a") { goto B; } }
浮躁的人容易问:我到底该学什么;----别问,学就对了; 浮躁的人容易问:JS有钱途吗;----建议你去抢银行; 浮躁的人容易说:我要中文版!我英文不行!----不行?学呀! 浮躁的人分两种:只观望而不学的人;只学而不坚持的人; 浮躁的人永远不是一个高手。