Efficiency of Bubble vs. Selection Sort

前端 未结 2 1315
-上瘾入骨i
-上瘾入骨i 2021-01-23 01:11

I understand that the big O values for Bubble Sort and Selection Sort are the same, (n)^2, but when I try to run both with an array of size 1000, the Bubble Sort takes 962037 sw

相关标签:
2条回答
  • 2021-01-23 01:55

    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.

    0 讨论(0)
  • 2021-01-23 01:57

    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.

    0 讨论(0)
提交回复
热议问题