Efficiency of Bubble vs. Selection Sort

情到浓时终转凉″ 提交于 2019-12-02 01:20:27

Because the complexity refers to the number of comparisons, not the number of swaps. Both need O(n^2) comparisons, but selection sort needs only n-1 swaps in the worstcase (O(n)), whereas bubblesort might need up to n*(n-1)/2 swaps (O (n^2)).

And even if the complexity would refer to the number of swaps - as the notation ignores constants (one could actually be 1000*n^2 + 500*n*log(n) + 100*n + 10, while the other could be n^2), both numbers could still differ by an abritrary large value.

Jaco

The Big O notation provides the asymptomatic cost, however, all additive values and constants are omitted. In addition, for a realistic comparison for small numbers, you need to look at the average number of comparisons. More specifically, Bubble sort requires, on average, n/4 swaps per entry , while Selection sort requires only 1, see this post for further details. The number of comparisons will also depend on the initial distribution, for example whether the data is semi-sorted or completely random.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!