Skip to content
Official PYQ · 2025

GATE CS 2025 Set 1 Q23 — Searching, Sorting, Hashing

Explain with AI

The pseudocode of a function fun ()\text{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 A[0,…,29]A[0, \ldots, 29] be an array storing 3030 distinct integers in descending order. The number of swap operations that will be performed, if the function fun ()\text{fun ()} is called with A[0,…,29]A[0, \ldots, 29] as argument, is _________. (Answer in integer)

View worked solution

Answer: 435:435

The given pseudocode implements the standard Bubble Sort algorithm:

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]
}

For an array of size nn, the outer loop runs for ii from 00 to n−2n-2. For each ii, the inner loop runs for jj from 00 to n−i−2n-i-2.

Since the array AA of size n=30n = 30 is initially sorted in descending order with distinct elements, every comparison A[j] > A[j+1] will evaluate to true. Thus, a swap operation is performed during every single comparison.

The total number of swaps is the sum of the number of inner loop iterations across all outer loop steps:

Total Swaps=∑i=0n−2(n−i−1)=(n−1)+(n−2)+⋯+1=n(n−1)2\text{Total Swaps} = \sum_{i=0}^{n-2} (n - i - 1) = (n-1) + (n-2) + \dots + 1 = \frac{n(n-1)}{2}

Substituting n=30n = 30 into the formula:

Total Swaps=30×292=15×29=435\text{Total Swaps} = \frac{30 \times 29}{2} = 15 \times 29 = 435

Therefore, the number of swap operations performed is 435.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Searching, Sorting, Hashing questions