一个快速找第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;
           }
        }
posted @ 2013-11-08 10:01  蚂蚁拉车  阅读(303)  评论(0编辑  收藏  举报