Question: Consider the following Bubble sort algorithm. Answer the following based on this algorithm for i 0 to n-2 do for j 0 to n-2-i do

  1. Consider the following Bubble sort algorithm. Answer the following based on this algorithm

for i 0 to n-2 do

for j 0 to n-2-i do

if (A[j+1] < A[j])

swap A[j] and A[j+1]

  1. Trace this algorithm with the following array. Show the array after each iteration of the ith loop. Show your work in detail.

5 4 7 3 1

  1. How many comparisons in total you made i.e. how many times the comparison statement if (A[j+1] < A[j]) is executed?

  1. How many swaps in total you made i.e. how many times the swap statement swap A[j] and A[j+1] is executed?

  1. Is Bubble sort stable? You can answer this with the array 2 2 1 3 5. Justify your answer.

  1. Compare the number of comparisons and swaps in 2.(b, c) and 1.(b, c)? What does this tell you about the efficiency of these algorithms?

  1. Trace the bubble sort algorithm for the following already sorted array. The algorithm still makes a lot of comparisons even though the list is already sorted. Make an improvement to the algorithm so that if a pass through the list makes no swaps, the program stops and declares that the list is already sorted. Write the improved algorithm.

5 7 8 10 17

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!