w3resource

C qsort() function

C qsort() function - Sort a table of data

Syntax qsort() function

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

The qsort() function is used to sort an array of nitems elements, each of width bytes in size. The base pointer is a pointer to the array to be sorted. The original array is overwritten by the qsort() function.

Parameters qsort() function

Name Description Required /Optional
base Start of target array. Required
nitems Array size in elements. Required
size Element size in bytes. Required
compar The pointer to the user-supplied routine for comparing two array elements and returning a value specifying their relationship. Required

Return value from qsort()

  • This function does not return any value.

Qsort calls the compare routine one or more times during the sort process, passing pointers to two array elements each time. When compare indicates that two elements are the same, their order in the sorted array is unspecified.

Name Description
< 0 element1 less than element2
0 element1 equivalent to element2
> 0 element1 greater than element2

Example: qsort() function

The following example shows the usage of qsort() function.

#include <search.h>
#include <string.h>
#include <stdio.h>

int compare( char **arg1, char **arg2 )
{
   /* Compare all of both strings: */
   return _strcmpi( *arg1, *arg2 );
}

int main( void )
{
   char *colors[] = {"red", "green", "pink", "orange", "red", "white", "black", "blue"};
   char *key = "red";
   char *key1 = "yellow";
   char *key2 = "black";
   int i;
   printf("Original array elements:\n");
   for(int i = 0; i < sizeof(colors)/sizeof(colors[0]); i++) {
        printf("%s ", colors[i]);
    }
    printf("\n\n");

   /* Sort using Quicksort algorithm: */
   qsort( (void *)colors, sizeof(colors)/sizeof(colors[0]), sizeof( char * ), (int (*)(const
   void*, const void*))compare );
   printf("Sorted array elements:\n");
   for( i = 0; i < sizeof(colors)/sizeof(colors[0]); ++i )    /* Output sorted list */
      printf( "%s ", colors[i] );

}

N.B.: This code is executed in windows 10

Output:

Original array elements:
red green pink orange red white black blue

Sorted array elements:
black blue green orange pink red red white

C Programming Code Editor:

Previous C Programming: C bsearch()
Next C Programming: C abs()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdlib/c-qsort.php