The time complexity description says it will be O(n) + O(n-1) which is equal to O(n).
O(n) may be correct but why are we saying time complexity will be O(n) + O(n-1)?
Would’nt it be O(n)+O(n-1)+O(n-2)+O(n-3)+…O(1)
because worse possible scenario applies for each index.
for i=0 we have to swap all items in the array
for i=1, we have to swap all items in the array minus 1 item on index 0 that was sorted in the previous step. So this step’s complexity will be O(n-1)
for i=2, we have to swap all items in the array except the first 2 indices that were sorted in previous steps. So this step’s complexity will be O(n-2)
for i=3, we have to swap all items in the array except the first 3 indices. So this step’s complexity will be O(n-3)
and so on.
so total complexity will be O(n) + O(n-1) + O(n-2) + O(n-3) + …
asymptomatically I believe this is still O(n) (can you verify that?)
but I just wanted to clarify the breakdown because in your answer it only had O(n) + O(n-1) .
Not the whole series.
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Cyclic Sort (easy) - Grokking the Coding Interview: Patterns for Coding Questions
Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Cyclic Sort (easy) - Grokking the Coding Interview: Patterns for Coding Questions