All Exams Test series for 1 year @ β‚Ή349 only
Question

The pseudocode of a function fun() is given below:

fun(int A[0, …, n-1]) {
    for i = 0 to n - 2
        for j = 0 to n - i - 2
            if (A[j] > A[j + 1])
                then swap A[j] and A[j + 1]
}

Let 𝐴[0, … ,29] be an array storing 30 distinct integers in descending order. The number of swap operations that will be performed, if the function fun() is called with 𝐴[0, … ,29] as argument, is __________. (Answer in integer)

To determine the number of swap operations performed by the function fun(), recognize that it implements a variation of the Bubble Sort algorithm. Given an array A[0, …, 29] sorted in descending order, we need to calculate the swaps to sort it in ascending order. Here's how:

Understanding Bubble Sort: The nested loops ensure that in each iteration of the outer loop, the largest element in the unsorted portion is "bubbled" to the end.

Loop Analysis: The outer loop runs from 0 to n-2 (i.e., 28), and the inner loop runs from 0 to n-i-2.

Initial State: The array is in descending order, requiring swaps at every comparison to sort ascendingly.

Counting Swaps: We can compute the swaps by summing the elements from 1 to n-1 since initially every pair (A[j], A[j+1]) is in the wrong order:

\(Total\ Swaps=\sum_{i=1}^{29}i=\frac{29\times(29+1)}{2}=435\)

Verification: The computed value, 435, fits the expected range (435,435).

Therefore, the function performs 435 swaps.

Was this answer helpful?

Important Questions from Sorting

  1. Consider an array $A = [10, 7, 8, 19, 41, 35, 25, 31]$. Suppose the merge sort algorithm is executed on array $A$ to sort it in increasing order. The merge sort algorithm will carry out a total of 7 merge operations.

    A merge operation on sorted left array $L$ and sorted right array $R$ is said to be void if the output of the merge operation is the elements of array $L$ followed by the elements of array $R$.

    The number of void merge operations among these 7 merge operations is __________. (answer in integer)
  2. What is the worst case time complexity of bubble sort?

  3. Any decision tree that sorts n elements has height

  4. You have to sort a list L, consisting of a sorted list followed by a few β€˜random’ elements. Which of the following sorting method would be most suitable for such a task ?

  5. If there are n integers to sort, each integer has d digits and each digit is in the set {1, 2, ..., k}, radix sort can sort the numbers in :

Need Expert Advice?

Start Your Preparation with Prepp Mobile App

Download the app from Google Play & App Store
Download the app from Google Play & App Store
Prepp Mobile App