Start free

Advanced · Sorting algorithms · 173 of 264

By length, then alphabet

Sort words by length, shortest first; words of the same length alphabetically (capital letters don't matter for the order).

Input: words on one line. Output: the sorted words.

Examples

Input
banana kiwi apple fig
Output
fig kiwi apple banana
Input
a B c
Output
a B c
Input
Delta alpha Charlie bravo
Output
alpha bravo Delta Charlie

One more test checks other inputs when you press Check.

Stuck? The idea behind sorting algorithms

Bubble sort swaps neighbours that are in the wrong order, pass after pass. Insertion sort takes each item in turn and slides it back into place among those before it. Merge sort splits the list, sorts each half and merges them.

These exercises ask for the steps, not just the result: write the algorithm yourself rather than calling sorted().

a = [5, 1, 4, 2]
for end in range(len(a) - 1, 0, -1):
    for i in range(end):
        if a[i] > a[i + 1]:
            a[i], a[i + 1] = a[i + 1], a[i]
print(a)

Watch for: Off-by-one: comparing a[i] with a[i + 1] means i must stop one before the end.

All the sorting algorithms exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More sorting algorithms exercises