Use qsort function to do quick sort

Syntax

C qsort function has the following syntax.

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

C qsort function is from header file stdlib.h.

Description

C qsort function sorts the array *buf using a Quicksort.

The number of elements in the array is specified by num, and the size (in bytes) of each element is described by size.

The function pointed to by compare is used to compare two elements of the array. The form of the compare function must be as follows:

int func_name(const void *arg1, const void *arg2);

Return value

C qsort function must return values as described here:

Comparison Value Returned
arg1 < arg2 < 0
arg1 == arg2 0
arg1 > arg2 > zero

The result array is sorted into ascending order with the lowest address containing the lowest element.

Example


#include <stdlib.h>
#include <stdio.h>
/* w ww  .  j av a  2 s  . c om*/
int num[10] = {
  1, 3, 6, 5, 8, 7, 9, 6, 2, 0
};

int comp(const void *, const void *);

int main(void)
{
  int i;

  printf("Original array: ");
  for(i=0; i<10; i++) printf("%d ", num[i]);

  qsort(num, 10, sizeof(int), comp);

  printf("Sorted array: ");
  for(i=0; i<10; i++) printf("%d ", num[i]);

  return 0;
}

/* compare the integers */
int comp(const void *i, const void *j)
{
  return *(int *)i - *(int *)j;
}

The code above generates the following result.





















Home »
  C Language »
    Function Reference »




assert.h
ctype.h
math.h
setjmp.h
signal.h
stdio.h
stdlib.h
string.h
time.h
wctype.h