How to analyse complexity of the given optimized bubble sort? -
this pseudo code of optimized bubble sort algorithm. have tried analyze time complexity, not sure cost of line 4 (if a[i-1] > a[i]). answer (n-1)+(n-2)+........+1 ? cost of lines 5 8?
1.for j = a.length 2 2. swapped = false 3. = 2 j 4. if a[i-1] > a[i] 5. temp = a[i] 6. a[i-1] = a[i] 7. a[i-1] = temp 8. swapped = true 9. if(!swapped) 10. break
the cost of lines 5 8 single iteration o(1).
the cost of loop @ lines 3-8 o(j-1).
the cost of whole sort in worst case o((n-1) + (n-2) + ... + 2) = o(n^2) (but of course in best case, when array sorted, cost o(n-1)).
by way, implementation of optimized bubble sort contains error: if
@ line 9 should inside outer loop, outside inner.
Comments
Post a Comment