OlveraeUNSW
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 a while, not an if — key may need to pass several larger elements, and if only shifts once. (2) The shift condition is a[j] > key (strictly greater); using >= still sorts but breaks stability. (3) Mind the bound j >= 0 so you do not run off the left end.

Input

  • Line 1: integer n (may be 0).
  • Line 2: n space-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