, , - O (n2),
BUBBLESORT(A)
1 for i = 1 to A.length - 1
2 for j = A.length downto i + 1
3 if A[j] < A[j - 1]
4 exchange A[j] with A[j - 1]
it is so important whether the array is sorted or not, there are no passes becoz, even if line 4 is skipped, lines 2 and 3 are executed propositionally up to n2 times
edit: I think I got it, but still I need to modify the algorithm by adding let say boolean variable is_exchange, setting it to false before entering the second cycle, and if it returns again after exiting the cycle, we will end, and in in this case, the time will be O (n) becoz the second cycle is executed n times
source
share