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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!