Question: The following code implements the Bubble Sort algorithm. If the bubble sort completes a pass where it doesn't perform any swaps, then we know the
The following code implements the Bubble Sort algorithm. If the bubble sort completes a pass where it doesn't perform any swaps, then we know the entire list must already be ordered, so we can immediately return from the function.
- First, modify the bubble_sort function to be more efficient by immediately stopping once the list is sorted (i.e. if there is an entire pass of the list in which no swaps are performed).
- Also, rename the function from bubble_sort to bubble_sort_fast to reflect this increase in efficiency
Your function should sort the list given into ascending order, but also return the number of comparisons and number of swaps that occurred during the sorting as a tuple in the order (number_of_comparisons, number_of_swaps)
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)
| Test | Result |
|---|---|
d = [89] comparison_count, swap_count = bubble_sort_fast(d) print(d) print(f'Comparisons: {comparison_count} Swaps: {swap_count}') | [89] Comparisons: 0 Swaps: 0 |
d = [2, 16, 7, 11, 1] comparison_count, swap_count = bubble_sort_fast(d) print(d) print(f'Comparisons: {comparison_count} Swaps: {swap_count}') | [1, 2, 7, 11, 16] Comparisons: 10 Swaps: 6 |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
