Question: Modify the insertion_sort algorithm so it will sort a list of strings by the following ordering criteria: shorter words are ordered as appearing before longer
Modify the insertion_sort algorithm so it will sort a list of strings by the following ordering criteria:
- shorter words are ordered as appearing before longer words
- words of equal length are ordered alphabetically
For example:
| Test | Result |
|---|---|
d = ['aaa', 'cccc', 'ee', 'bb', 'bbbb', 'd'] insertion_sort(d) print(d) | ['d', 'bb', 'ee', 'aaa', 'bbbb', 'cccc'] |
def compare(data, a, b): """Returns True if element at index a > element at index b""" return data[a] > data[b]
def swap(data, a, b): """Swaps the element at index a with element at index b""" data[a], data[b] = data[b], data[a]
def insertion_sort(data): """Sorts a list""" for index in range(1, len(data)): position = index while position > 0 and compare(data, position - 1, position): swap(data, position - 1, position) position -= 1
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
