zoukankan      html  css  js  c++  java
  • 一个快速找第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;
               }
            }
  • 相关阅读:
    响应式笔记(1)
    javascript复制文章加版权声明代码
    div的水平和垂直居中
    javascript随机打乱数组
    javascript操作字符串的方法
    《Javascript高级程序设计》读书笔记(1-3章)
    一个将 footer 保持在底部的最好方法
    Python内置的字符串处理函数整理
    c c++怎么判断一个字符串中是否含有汉字
    shell的if判断
  • 原文地址:https://www.cnblogs.com/xuekai-to-sharp/p/3413737.html
Copyright © 2011-2022 走看看