Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Turbo C - <b>qsort() perform quick sort</b> http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
qsort()                  Perform Quick Sort

 #include   <search.h>                   Required for declarations only

 void       qsort(base,num,width,compare);
 char       *base;                       Pointer to base of search data
 unsigned   num, width;                  Number and width of elements
 int        (*compare)();                Pointer to compare function

    qsort() uses a quick-sort algorithm to sort an array of 'num'
    elements.  Each element is 'width' bytes in size.  'base' points to
    the base of the array to be sorted.  qsort() overwrites this array
    with the sorted elements.

    'compare' points to a user-supplied routine that qsort calls one or
    more times, each time passing it pointers to two array elements to be
    compared. 'compare' returns one of the following values, based on the
    results of the comparison:

                 < 0:        'element1' <  'element2'

                   0         'element1' == 'element2'

                 > 0         'element1' >  'element2'

    Returns:    There is no return value.

      Notes:    qsort() will make repeated calls to the 'compare' routine
                during the search.  On each call to 'compare', 'key' will
                be compared with one of the elements of 'base'.

  -------------------------------- Example ---------------------------------

    The following statements print out an array, sort the array and print
    it again.

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

        int vals[] = {10,90,30,70,50,60,40,80,20,100};
        int num = 10, x;
        int cmp();

        main()
        {
            for (x = 0; x < num; x++)
                printf("%d ",vals[x]);
            printf("\n");
            qsort(vals,num,sizeof(int),cmp);
            for (x = 0; x < num; x++)
                printf("%d ",vals[x]);
        }

      int cmp(n1,n2)
      int *n1;
      int *n2;
      {
          return(*n1 - *n2);
      }

See Also: bsearch() lfind() lsearch()

Online resources provided by: http://www.X-Hacker.org --- NG 2 HTML conversion by Dave Pearson