Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Modify the original Insertion Sort code shown below so that it will print out the length of the list, total number of comparisons, and total
Modify the original Insertion Sort code shown below so that it will print out the length of the list, total number of comparisons, and total number of swaps needed to sort the list given.
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 the list into ascending order""" 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
example:
d = [75, 64, 90, 73, 65] insertion_sort(d) | Length: 5 Comparisons: 9 Swaps: 6 |
d = [50, 63, 11, 79, 22, 70, 65, 39, 97, 48] insertion_sort(d) | Length: 10 Comparisons: 27 Swaps: 19 |
d = [73, 100, 58, 69, 87, 41, 25, 71, 68, 37, 68, 3, 63, 41, 0, 21, 32, 2, 25, 9, 16, 68, 75, 60, 62, 16, 59, 95, 10, 76, 49, 62, 90, 14, 61, 47, 1, 73, 44, 98, 59, 5, 83, 72, 3, 30, 6, 19, 61, 12] insertion_sort(d) | Length: 50 Comparisons: 728 Swaps: 684 |
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started