Algorithm BubbleSort works by making repeated passes

Chapter 3, Problem 13

(choose chapter or problem)

Get Unlimited Answers
QUESTION:

Algorithm BubbleSort works by making repeated passes through a list; on each pass, adjacent elements that are out of order are exchanged. At the end of pass 1, the maximum element has bubbled up to the end of the list and does not participate in subsequent passes. The following algorithm is called initially with j = n. BubbleSort(list L; integer j) //recursively sorts the items from 1 to j in list L into increasing order if j = 1 then sort is complete, write out the sorted list else for i = 1 to j 1 do if L[i] > L[i + 1] then exchange L[i] and L[i + 1] end if end for BubbleSort(L, j 1) end if end function BubbleSort Section 3.3 Analysis of Algorithms 215 a. Walk through algorithm BubbleSort to sort the list 5, 6, 3, 4, 8, 2. b. Write a recurrence relation for the number of comparisons of list elements done by this algorithm to sort an n-element list. c. Solve this recurrence relation.

Questions & Answers

QUESTION:

Algorithm BubbleSort works by making repeated passes through a list; on each pass, adjacent elements that are out of order are exchanged. At the end of pass 1, the maximum element has bubbled up to the end of the list and does not participate in subsequent passes. The following algorithm is called initially with j = n. BubbleSort(list L; integer j) //recursively sorts the items from 1 to j in list L into increasing order if j = 1 then sort is complete, write out the sorted list else for i = 1 to j 1 do if L[i] > L[i + 1] then exchange L[i] and L[i + 1] end if end for BubbleSort(L, j 1) end if end function BubbleSort Section 3.3 Analysis of Algorithms 215 a. Walk through algorithm BubbleSort to sort the list 5, 6, 3, 4, 8, 2. b. Write a recurrence relation for the number of comparisons of list elements done by this algorithm to sort an n-element list. c. Solve this recurrence relation.

ANSWER:

Step 1 of 9

(a)

L= 5, 6, 3, 4, 8, 2

j=6

In the first pass, the BubbleSort is called as BubbleSort(L: [5, 6, 3, 4, 8, 2], 6)

The ‘for’ loop runs as below:

For i=1, compare 5 and 6. The new list is 5, 6, 3, 4, 8, 2.

For i=2, compare 6 and 3. The new list is 5, 3, 6, 4, 8, 2.

For i=3, compare 6 and 4. The new list is 5, 3, 4, 6, 8, 2.

For i=4, compare 6 and 8. The new list is 5, 3, 4, 6, 8, 2.

For i=5, compare 8 and 2. The new list is 5, 3, 4, 6, 2, 8.

Add to cart


Study Tools You Might Need

Not The Solution You Need? Search for Your Answer Here:

×

Login

Login or Sign up for access to all of our study tools and educational content!

Forgot password?
Register Now

×

Register

Sign up for access to all content on our site!

Or login if you already have an account

×

Reset password

If you have an active account we’ll send you an e-mail for password recovery

Or login if you have your password back