Continue learning
Practice related DSA questions in the same topic.
Return the ascending sequence by repeatedly fixing inverted neighbouring pairs.
Return the ascending sequence by repeatedly fixing inverted neighbouring pairs.
def solve(values, target): a = values.copy() end = (len(a) - 1) while (end > 0): changed = 0 i = 0 while (i < end): j = (i + 1) if (a[i] > a[j]): a[i], a[j] = a[j], a[i] changed = 1 i = (i + 1) if (changed == 0): break end = (end - 1) return aCompare neighbouring positions 0 and 1.
Compare neighbouring positions 0 and 1.
In a line-up, taller neighbours step back until the tallest reaches the end.
The largest unplaced value reaches the end of each full pass.
O(n²) worst, O(n) best time · O(n) returned copy, O(1) auxiliary auxiliary space
Worked example · {"values":[7,2,5,3],"target":0} ⇒ [2,3,5,7]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[1,2,2],"target":0} ⇒ [1,2,2]
An early-exit flag must be reset at the start of each pass.
What input gives this implementation a linear best case?