LearnFrenzy
Sign in Take a free test

C Library Functions · Predict the Output · Question 9

qsort with a descending comparator Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>
#include <stdlib.h>

int desc(const void *a, const void *b) {
    int x = *(const int *) a, y = *(const int *) b;
    return (y > x) - (y < x);
}

int main(void) {
    int v[] = {5, -2, 9, 0, 9, 3};
    qsort(v, 6, sizeof v[0], desc);
    for (int i = 0; i < 6; i++)
        printf("%d ", v[i]);
    printf("\n");
    return 0;
}
  • A 9 9 5 3 0 -2 Correct
  • B -2 0 3 5 9 9
  • C 9 5 3 0 -2
  • D 5 -2 9 0 9 3
Correct Answer: Option A

Swapping the roles of x and y reverses the order. Duplicates stay in the result.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links