Comparator function of qsort() in C


In C, we get the qsort() function. This is used to sort some array using quicksort technique. In this function we have to pass the comparator function. This comparator function takes two arguments. Then compares them and get the relative order between them. These two arguments are pointers, and type casted to const void*. The syntax is like below −

int comparator(const void* p1, const void* p2);

The return values are of three types −

  • Less than 0. The element pointed by p1 will go before the second one.
  • Equal to 0. Two values are same.
  • Greater than 0. The element pointed by p1 will go after the second one

Example

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct {
   char title[50];
   int pages;
   float price;
}
book;
int compareBook(book b1, book b2){
   if(b1.price < b2.price){
      return 0;
   }
   return 1;
}
main() {
   int i;
   book book_arr[5];
   strcpy(book_arr[0].title, "C Programming");
   book_arr[0].pages = 260;
   book_arr[0].price = 450;
   strcpy(book_arr[1].title, "DBMS Guide");
   book_arr[1].pages = 850;
   book_arr[1].price = 775;
   strcpy(book_arr[2].title, "Learn C++");
   book_arr[2].pages = 350;
   book_arr[2].price = 520;
   strcpy(book_arr[3].title, "Data Structures");
   book_arr[3].pages = 380;
   book_arr[3].price = 430;
   strcpy(book_arr[4].title, "Learn Python");
   book_arr[4].pages = 500;
   book_arr[4].price = 300;
   qsort((void*)book_arr, 5, sizeof(book_arr[0]), compareBook);
   for(i = 0; i<5; i++) {
      printf("%s\t\t%d\t\t%f\n",book_arr[i].title, book_arr[i].pages, book_arr[i].price);
   }
}

Output

Learn Python             500       300.000000
Data Structures          380       430.000000
C Programming            260       450.000000
Learn C++                350       520.000000
DBMS Guide               850       775.000000

Updated on: 30-Jul-2019

954 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements