📜  门| GATE-CS-2001 |问题 23(1)

📅  最后修改于: 2023-12-03 15:12:39.721000             🧑  作者: Mango

GATE-CS-2001 Problem 23
Problem Description

Consider the following C function:

void swap(int *x, int *y)
{
  int *temp = x;
  x = y;
  y = temp;
}

In order to exchange the values of two variables x and y.

(a) Write a suitable C function that uses the swap function defined above to sort an array of integers in ascending order.

(b) What modification is required to be made if descending order of the array is to be sorted?

Solution

Part (a)

The swap function defined above will not actually swap the values of two variables, as it only swaps their pointers. Thus, we need to pass the pointers of the variables to the swap function in order to exchange their values. To sort an array of integers in ascending order, we can implement the following sortAsc function:

void sortAsc(int arr[], int n)
{
  int i, j, min_idx;

  for (i = 0; i < n-1; i++)
  {
    min_idx = i;
    for (j = i+1; j < n; j++)
    {
      if (arr[j] < arr[min_idx])
        min_idx = j;
    }
    swap(&arr[min_idx], &arr[i]);
  }
}

This function uses a selection sort algorithm to iterate through the array and find the minimum value in each pass, swapping it with the current position until the array is sorted in ascending order. The swap function is called with the addresses of the elements to be swapped, which will correctly change their values.

Part (b)

If we need to sort the array in descending order, we can modify the sortAsc function by changing the comparison operator in the inner loop to > instead of <:

void sortDesc(int arr[], int n)
{
  int i, j, max_idx;

  for (i = 0; i < n-1; i++)
  {
    max_idx = i;
    for (j = i+1; j < n; j++)
    {
      if (arr[j] > arr[max_idx])
        max_idx = j;
    }
    swap(&arr[max_idx], &arr[i]);
  }
}

This function will now find the largest value in each pass and swap it with the current position until the array is sorted in descending order.

Conclusion

In conclusion, the swap function is not suitable for actually exchanging the values of two variables, and must be modified to be useful. We can use it to sort an array of integers in both ascending and descending order by implementing selection sort algorithms with different comparison operators.