This algorithm is actually cubic (O(n^3) where n = length of list) in the worst case scenario. Imagine the following input: list = [5,4,3,2,1]
.
First iteration: list[0] > list[1]. The swap is made such that list = [4,5,3,2,1]
, and i
is reduced to -1, so the loop starts over.
Second iteration: list[0] < list[1].
Third iteration: list[1] > list[2]. The swap is made such that list = [4,3,5,2,1]
, and i
is reduced to -1, so the loop starts over.
Fourth iteration: list[0] > list[1]. The swap is made such that list = [3,4,5,2,1]
, and i
is reduced to -1, so the loop starts over.
The same pattern continues: we will need 6 more iterations to bring 2 to the start of the list, 10 iterations for 1, and 5 to skim over the list once it's all sorted. Overall 4+6+10+5=25 which is 5^2. So why n^3 and not n^2?
Intuition:
For a list that sorted in reverse like the one in the above example, we would need to bring each element to the head of the list from greatest to smallest. The j'th element in the initial list is the j'th greatest overall and will need (1+2+...+j)=O(j^2) steps to bring to the head of the list.
Therefore, in order to reverse the list of length n, we need approximately (1^2 + 2^2 + ... + n^2) steps. That is the sum of squares from 1 to n which is O(n^3) - if you don't know why, it's a very well-known formula in arithmetics: sum of squares.
Disclaimer: Of course, it wouldn't be exactly n^3 steps, but it will be approximately so (which is after all the definition of Big-O notation. It will be closer to n^3 the bigger n gets).