Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database And Expert Systems Applications 19th International Conference Dexa 2008 Turin Italy September 2008 Proceedings Lncs 5181

Authors: Sourav S. Bhowmick ,Josef Kung ,Roland Wagner

2008th Edition

3540856536, 978-3540856535

More Books

Students also viewed these Databases questions