确定性选择的时间复杂度

时间:2021-03-08 21:43:49

标签: algorithm sorting time-complexity

假设我做了 k 个组。由于输入数组的大小不是常数,一个组中的元素数将为 n/k。排序这将需要 (n/k)log(n/k)。对于 k 个组,它将是 (n)log(n/k),即 O(nlogn)。那怎么算法是O(n)呢?

编辑:来自 Gfg https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array-set-3-worst-case-linear-time/amp/

kthSmallest(arr[0..n-1], k)
1) Divide arr[] into ⌈n/5⌉ groups where size of each group 
is 5 except possibly the last group which may have less     
than 5 elements.
2) Sort the above created ⌈n/5⌉ groups and find median 
of all groups. Create an auxiliary array ‘median[]’ and 
store medians of all ⌈n/5⌉ groups in this median array.
// Recursively call this method to find median of 
median[0..⌈n/5⌉-1]
3) medOfMed = kthSmallest(median[0..⌈n/5⌉-1], ⌈n/10⌉)
4) Partition arr[] around medOfMed and obtain its 
position.
pos = partition(arr, n, medOfMed)
5) If pos == k return medOfMed
6) If pos > k return kthSmallest(arr[l..pos-1], k)
7) If pos < k return kthSmallest(arr[pos+1..r], k-pos+l-1)

1 个答案:

答案 0 :(得分:1)

您不是在对每组中的元素进行排序,您只是在寻找它们的中位数,即 O(n/k)(这理论上是在 n/k 的小且恒定值上完成的,然后才考虑如O(1))。因此,您必须运行 O(n/k) 算法 k 次,结果为 O(n)

请注意,即使您进行排序,由于该算法使用常量大小的组,那么每个组的大小:n/k = C(对于某些常量 C) ,你会得到:O(nlog(n/k)) = O(nlog(C)) = O(n)