Let swap() be a function that swaps two elements using their addresses.…

2015

Let swap() be a function that swaps two elements using their addresses. Consider the following C function.

void fun (int arr [], int n )

{

for (int i = 0; i < n; i+=2)

{

if (i>0 && arr[i-1] > arr[i])

swap(&arr[i], &arr[i-1]);

if (i<n-1 && arr[i] < arr[i+1])

swap(&arr[i], &arr[i+1]);

}

}

If an array {10, 20, 30, 40, 50, 60, 70, 80} is passed to the function, the array is changed to

  1. A.

    {20, 10, 40, 30, 60, 50, 80, 70}

  2. B.

    {10, 30, 20, 40, 60, 50, 80, 70}

  3. C.

    {10, 20, 30, 40, 50, 60, 70, 80}

  4. D.

    {80, 70, 60, 50, 40, 30, 20, 10}

Attempted by 13 students.

Show answer & explanation

Correct answer: A

The loop runs for i = 0, 2, 4, 6. At i = 0, 10 < 20, so 10 and 20 are swapped. At i = 2, 30 < 40, so 30 and 40 are swapped. At i = 4, 50 < 60, so 50 and 60 are swapped. At i = 6, 70 < 80, so 70 and 80 are swapped. The first if condition is false in each later case because the previous odd element is smaller. Final array: {20, 10, 40, 30, 60, 50, 80, 70}.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir