简体   繁体   English

QuickSelect平均时间复杂度O(n)[如何?]

[英]QuickSelect average time complexity O(n) [HOW?]

I was learning QuickSelect to find Kth Smallest Number. 我在学习QuickSelect来查找Kth最小数字。 I understood the program. 我了解该程序。 But I am stuck with how the average time complexity of QuickSelect is O(n). 但是我对QuickSelect的平均时间复杂度如何为O(n)感到困惑。

I have tried the code in Java and it worked. 我已经尝试过用Java编写代码,并且可以正常工作。 But I am stuck with time complexity. 但是我对时间的复杂性感到困惑。

public class KthSmallestNumberUsingQuickSelect {

    int findKthNumber(int arr[], int left, int right, int k ) {
        if(k > 0 && k <= right - left + 1) {

            int pos = partition(arr,left,right);

            if(pos - left == k - 1)
                return arr[pos];

            if(pos - left > k - 1)
                return findKthNumber(arr, left, pos - 1, k);
            System.out.println(k - pos + left - 1);
            return findKthNumber(arr, pos + 1, right, k - pos + left - 1);
        }
        return Integer.MAX_VALUE;
    }

    int partition(int arr[], int left, int right) {
        int i = left ;
        int j;
        int x = arr[right];
        int temp = 0;

        for(j=left; j<right; j++ ) {
            if(arr[j] <= x) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

                i++;
            }
        }
        temp = arr[i];
        arr[i] = x;
        arr[right] = temp;

        return i;
    }

    public static void main(String[] args) {
        KthSmallestNumberUsingQuickSelect kq = new KthSmallestNumberUsingQuickSelect();


        int arr[] =  {7,10,4,3,20,15};
        int k = 3;

        System.out.println(kq.findKthNumber(arr,0,arr.length-1, k));
    }
}

How is the average time complexity O(n)? 平均时间复杂度O(n)如何? Can anyone explain this to me in detail? 谁能向我详细解释一下?

I think your question is not QuickSelect specific. 我认为您的问题不是QuickSelect特有的。 You are asking what is the difference between the big O notation and the average Theta (Θ) notation. 您在问大O表示法和平均Theta(Θ)表示法之间有什么区别。

The big O notation describes the biggest potential complexity that the algorithm will use. 大O符号表示算法将使用的最大潜在复杂性。

On the other hand the Θ notation is the average complexity out all the possible combinations of the input for the problem. 另一方面,Θ表示法是问题的所有可能输入组合中的平均复杂度。

There is also the omega (Ω) notation for the best case complexity. 此外,还具有欧米茄(Ω)表示法,以实现最佳的案例复杂性。

The quick select algorithm follows similar complexity to quick sort and you are right the big O notation for both is O(n^2), but in the average case they are better. 快速选择算法具有与快速排序类似的复杂度,并且您都对O表示的大O表示法是O(n ^ 2),但在一般情况下,它们更好。

If you need more specific explanation why the average case is linear read the answer in this post . 如果您需要更具体的解释,为什么一般情况下是线性阅读本答案职位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM