qsort C Library Function

The function qsort sorts an array(pointed by base) of num elements using compare function to determine the order of any two element. It doesn’t return anything, instead rearrange elements of input array such that whole array becomes sorted.

Here is the return value of comparison function int compare(const void *x, const void *y).
  • If *x < *y, compare function should return an integer < 0.
  • If *x == *y, compare function should return 0.
  • If *x > *y, compare function should return an integer > 0.

Function prototype of qsort

void qsort(void *base, size_t num, size_t size, int (*compare)(const void *, const void*));

size_t is an unsigned integer type.

  • base : This is a pointer to the first element of the array to be sorted, type-casted to a void*.
  • num : This is the number of elements in the array pointed by base.
  • size : This is size in bytes of each element of the array.
  • compare : This is a pointer to a function that compares two elements.

Return value of qsort

NONE

C program using qsort function

The following program shows the use of qsort function to sort and array of integers.

qsort C Library Function

#include <stdio.h>
#include <stdlib.h>
 
/* Function to compare two objects */
int compare(const void *x, const void *y){
   return (*(int*)x - *(int*)y);
}
 
int main(){
    int array[50], counter, n;
    int *ptr;
     
    printf("Enter number of elements\n");
    scanf("%d", &n);
 
    printf("Enter %d numbers\n", n);
    for(counter = 0; counter < n; counter++){
        scanf("%d", &array[counter]);
    }
     
    /* Sort input numbers using qsort function */
    qsort (array, n, sizeof(int), compare);
     
    /* Printing numbers in sorted order */
    printf("Numbers in sorted order\n");
    for(counter = 0; counter < n; counter++){
        printf("%d ", array[counter]);
    }
     
    return 0;
}

Output

Enter number of elements
8
Enter 8 numbers
2 8 1 3 7 4 6 5
Numbers in sorted order
1 2 3 4 5 6 7 8