User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:stdlib.h:qsort

qsort

#include <stdlib.h>
    void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*));

Description

base = Pointer to elements
nitems = Number of elements
size = Size of one element
compar = Pointer to comparison function

qsort will sort an array of elements
with using a comparison function

qsort C Sourcecode Example

/* 
 * qsort example code
 * http://code-reference.com/c/stdlib.h/qsort 
 */
 
#include <stdio.h>
#include <stdlib.h>
 
int compare(const int *n1, const int *n2)
{
  if (*n1 == *n2) { return  0; }
  else if (*n1 <  *n2) { return -1; }
  else if (*n1 >  *n2) { return  1; }
  else
  return 0;
}
 
 
int main( void )
{
  int array[]=  {42,43,44,5,23,992,1231,3133,3,9274};
  int i;
 
  for (i=0; i<10; i++){
     printf ("%d ",array[i]);
  }
  printf(" not sorted\n");
  qsort(array, 10, sizeof(int), (void *)compare );
 
 for (i=0; i<10; i++){
     printf ("%d ",array[i]);
  }
  printf(" Sorted with qsort\n");
 
return 0;
}

output of qsort example

  user@host:~/code-reference.com#  ./qsort 
  42 43 44 5 23 992 1231 3133 3 9274  not sorted
  3 5 23 42 43 44 992 1231 3133 9274  Sorted with qsort
  

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
c/stdlib.h/qsort.txt · Last modified: 2024/02/16 01:04 (external edit)

Impressum Datenschutz