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 swaps to sort the array, while Selection Sort only takes 988 swaps to sort the array. Why are these different?
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.