Back to problems
COMP2521
Sorting: Ascending Order
Sorting: put the array in ascending order
Read a list of integers and print them sorted smallest to largest. Any algorithm works — the scaffold here is insertion sort: keep a sorted region on the left and insert each next element into its place.
Complete sortAsc: starting from i = 1, take key = a[i], shift the elements on the left that are greater than key one step right, then drop key into the gap.
Pitfalls (straight from the bug lab): (1) the inner loop must be awhile, not anif— key may need to pass several larger elements, andifonly shifts once. (2) The shift condition isa[j] > key(strictly greater); using>=still sorts but breaks stability. (3) Mind the boundj >= 0so you do not run off the left end.
Input
- Line 1: integer
n(may be0). - Line 2:
nspace-separated integers.
Output
- One line: the array in ascending order, a space after each value.
Example: input 5 / 5 2 8 1 9 -> 1 2 5 8 9 .
Samples
stdin
5 5 2 8 1 9
expected
1 2 5 8 9
stdin
1 42
expected
42
c-dcc
14