Question: Write a function called compare_sorts which accepts a list of integers and produces a summary of the number of comparisons and swaps that are required
Write a function called compare_sorts which accepts a list of integers and produces a summary of the number of comparisons and swaps that are required to sort the integers using Bubble Sort and Selection Sort. Use the algorithms given previously for each of the sorts. The output should appear in the format:
-- Comparisons: Swap:
Where the name of the sorts are Bubble Sort and Selection Sort. You should print the output in the same order as the list of sorts given previously.
For example:
| Test | Result |
|---|---|
d = [40] compare_sorts(d) | Bubble Sort -- Comparisons: 0 Swap: 0 Selection Sort -- Comparisons: 0 Swap: 0 |
d = [55, 53, 58, 64, 69] compare_sorts(d) | Bubble Sort -- Comparisons: 10 Swap: 1 Selection Sort -- Comparisons: 10 Swap: 4 |
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 bubble_sort( data ): """Sorts a list into ascending order""" n = len( data ) for i in range( n - 1, 0, -1 ): for j in range( i ) : if compare(data, j, j+1) : swap(data, j, j+1)
def selection_sort(data): """Sorts a list into ascending order""" for fill_slot in range(len(data) - 1, 0, -1): pos_of_max = 0 for i in range(1, fill_slot + 1): if compare(data, i, pos_of_max): pos_of_max = i swap(data, fill_slot, pos_of_max) def insertion_sort(data): """Sorts a 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
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
