Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Look at the following code fragment. Identify what it is doing (be clear and com

ID: 3537228 • Letter: L

Question

Look at the following code fragment. Identify what it is doing (be clear and complete). Run various scenarios (hand simulations). Decide what the best & worst case conditions are. Give the Big O of this fragment.

            bool done = false;

            int temp = 0;

            While (!done) {

            done = true;

            for (int i = 0; i<5; i++)

                if (array[i] < array [i+1] {

                        done = false;

                        temp = array[i+1];

                        array[i+1] = array [i];

                        array[i]= temp;

                } // fi

  } // while

Explanation / Answer

this code will sort the array elements in descending order. THIS code is just like a bubble sort.

In this code at each itration smallest element is placed in its proper position.


first itration -- first smallest element

second itration --2nd smallest element and so on.


BEST Case complexity = O(n)


since In this code if array elements are alredy in descending order then there will be no swapping and the total no of comparision = n time

worst Case complexity = O(n^2)

since In this code if array elements are alredy in ascending order then

there will be n no of swapping for n number of times so total no of comparision = n X n time = n^2


Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote