简体   繁体   English

比较选择排序中的平均情况和最坏情况交换的数量

[英]Comparing number of average case and worst case swaps in selection sort

I came across following problem:我遇到了以下问题:

State true or false:陈述真假:
In selection sort, total swaps in average case >= total swaps in worst case在选择排序中,平均情况下的总掉期 >= 最坏情况下的总掉期

After pondering a bit and trying out some examples, I reached following conclusions:经过一番思考和尝试,我得出了以下结论:

In selection sort, worst case = best case = avg case = O(n^2).在选择排序中,最坏情况 = 最好情况 = 平均情况 = O(n^2)。

In selection sort, time complexity is determined by number of comparisons which is always n(n-1)/2 = O(n^2)在选择排序中,时间复杂度由比较次数决定,总是 n(n-1)/2 = O(n^2)

So we cannot say, total swaps in average case>=total swaps in worst case.所以我们不能说,平均情况下的总掉期>=最坏情况下的总掉期。 On the other hand, minimum number of swaps happen when array is already sorted.另一方面,当数组已经排序时,会发生最小交换次数。 And maximum number of swaps happen when first half of the array contains n/2 largest elements in reverse sorted order and second half of the array contains n/2 smallest elements in sorted order.当数组的前半部分包含倒序排列的 n/2 个最大元素而数组的后半部分包含排序顺序的 n/2 个最小元素时,就会发生最大交换次数。 However this will not necessarily always lead to n-1 swaps.然而,这不一定总是导致 n-1 交换。 Instead it might lead to n-1, n-2 or even n-3 swaps as explained in the figure below:相反,它可能会导致 n-1、n-2 甚至 n-3 次交换,如下图所示: 在此处输入图片说明

I am correct with above thinking?我上面的想法是正确的吗?

An average case cannot exceed the worst case, this is impossible.平均情况不能超过最坏情况,这是不可能的。

The average case can equal the worst case, provided all cases have the same complexity.平均情况可以等于最坏情况,前提是所有情况都具有相同的复杂性。

Depending on how exactly you implement SelectionSort, you have two situations:根据您实现 SelectionSort 的具体方式,您有两种情况:

  • if you "blindly" swap after every selection, the count of swaps is N-1 and is constant;如果您在每次选择后“盲目地”交换,则交换次数为 N-1 并且是恒定的;

  • if you swap only when the selected element is not already in place, the count of swaps can be less (in the best case - a sorted array - the count is 0).如果仅在所选元素尚未就位时进行交换,则交换次数可能会更少(在最好的情况下 - 排序数组 - 计数为 0)。

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

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