且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

最坏情况下的时间复杂度为这个愚蠢的排序?

更新时间:2021-10-03 00:43:49

对于初学者来说,总和

(1 + 2 + 3 + ... + N)+(1 + 2 + 3 + ... + N - 1)+ ... + 1

(1 + 2 + 3 + ... + n) + (1 + 2 + 3 + ... + n - 1) + ... + 1

实际上不是为O(n)。相反,它是为O(n 3 )。你可以看到这一点,因为总和1 + 2 + ... + N = O(N 2 ,并且有n他们每个人的副本,您可以更正确地表明,这种求和是与西塔。 (正 3 )通过查看第一n / 2这些术语的每一个这些术语的至少是1 + 2 + 3 + ... + N / 2 =&的Theta;(正 2 ),所以有n个东西是与西塔/ 2份;(N 2 ),给人一种紧约束的和西塔(N 3

is not actually O(n). Instead, it's O(n3). You can see this because the sum 1 + 2 + ... + n = O(n2, and there are n copies of each of them. You can more properly show that this summation is Θ(n3) by looking at the first n / 2 of these terms. Each of those terms is at least 1 + 2 + 3 + ... + n / 2 = Θ(n2), so there are n / 2 copies of something that's Θ(n2), giving a tight bound of Θ(n3).

我们可以上界,该算法的总运行时间在为O(n 3 ),他指出,每一个交换减少阵列中的反转的一个数目(反转是一对元素的出来的地方)。可以有最多为O(n 2 )在一个数组倒置和排序后的数组中有没有倒(你知道为什么吗?),所以有至多为O(n 2 )越过数组,每个花费最多O(n)的工作。它们共同提供了一个界为O(n 3 )。

We can upper-bound the total runtime of this algorithm at O(n3) by noting that every swap decreases the number of inversions in the array by one (an inversion is a pair of elements out of place). There can be at most O(n2) inversions in an array and a sorted array has no inversions in it (do you see why?), so there are at most O(n2) passes over the array and each takes at most O(n) work. That collectively gives a bound of O(n3).

因此​​,与西塔(N 3 )你已经​​确定最差情况下的运行时间是渐近紧,所以算法的时间为O(N 3 )和有最坏情况运行时和西塔。(N 3

Therefore, the Θ(n3) worst-case runtime you've identified is asymptotically tight, so the algorithm runs in time O(n3) and has worst-case runtime Θ(n3).

希望这有助于!