• Randomized QuickSelect


    In this blog, we give a solution for Quick Select.

    Here, we have an improvement. The idea is to randomly pick a pivot element.

    Main difference is how we implement partition.

    Java Random

    public int nextInt(int bound)

    Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).
    int idx = new Random().nextInt(nums.length);
    int random = (nums[idx]);

    Codes

     1 public class Solution {
     2     private int partition(int[] nums, int start, int end) {
     3         int pivot = nums[end];
     4         int currentSmaller = start - 1;
     5         for (int i = start; i < end; i++) {
     6             if (nums[i] < pivot) {
     7                 currentSmaller++;
     8                 swap(nums, i, currentSmaller);
     9             }
    10         }
    11         currentSmaller++;
    12         swap(nums, end, currentSmaller);
    13         return currentSmaller;
    14     }
    15 
    16     public int randomPartition(int[] nums, int start, int end) {
    17         int length = end - start + 1;
    18         int idx = new Random().nextInt(length);
    19         int randomIndex = idx + start;
    20         swap(nums, last, randomIndex);
    21         partition(nums, start, end);
    22     }
    23 }

    The assumption in the analysis is, random number generator is equally likely to generate any number in the input range.

    The worst case time complexity of the above solution is still O(n2). In worst case, the randomized function may always pick a corner element. The expected time complexity of above randomized QuickSelect is Θ(n), see CLRS book or MIT video lecture for proof. 

  • 相关阅读:
    【u020】Couple number
    【HDU5748】Bellovin
    【CF706C】Hard problem
    【u021】广义斐波那契数列
    【u024】没有上司的舞会
    【u025】贝茜的晨练计划
    【u026】房间最短路问题
    Core Data 数据出现Fault
    Core Data 数据出现Fault
    非常优秀的Javascript(AJAX) 开发工具:Aptana
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4865572.html
Copyright © 2020-2023  润新知