Sort a list of whole numbers from smallest to largest. Write the sort yourself (bubble or selection sort) instead of using sorted(); the checker only sees the output, so this is up to you.
What to build
A sort that you write yourself.
Requirements
- Read the numbers.
- Sort them with your own bubble or selection sort.
Input
The first line has n (1 to 300). The second line has n whole numbers.
Output
The sorted numbers, separated by spaces.
Constraints
n is from 1 to 300.
Example
Input:
4
5 2 4 1
Output:
1 2 4 5
Why it works
Writing the swaps yourself shows exactly why this kind of sort takes about n²/2 comparisons.
Examples
Example 1 · Input
4 5 2 4 1
Expected output
1 2 4 5
Example 2 · Input
1 7
Expected output
7
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Bubble sort: compare neighbours and swap them when they are in the wrong order.
Hint 2
a, b = b, a swaps two values.
Solution
Show one correct solution (try it yourself first)
n = int(input())
nums = [int(x) for x in input().split()]
for i in range(n - 1):
for j in range(n - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
print(" ".join(str(x) for x in nums))