Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Zortech C++ Language Reference - qsort http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
   qsort

   Usage
   include <stdlib.h>

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

   Description
   qsort  is  an implementation of the quick-sort algorithm. It  sorts  a
   table of elements.

   base      Points to the element at the base of the table.

   nel       The number of elements in the table.

   size      The size in bytes of one table element.

   compar    The name of the comparison function, which is  called  with
             two  arguments  that point to the elements  being  compared.
             compar must be written by the programmer and must return  an
             integer  that is less than, equal to, or greater  than  zero
             according  to  a  comparison of the first  argument  to  the
             second.

   Example
   #include <stdio.h>
   #include <stdlib.h>
   #include <string.h>
   #define MAXL 10
   unsigned char *line[MAXL];

   comp(unsigned char **a,unsigned char **b)
   {
        return strcmp(*a,*b);
   }

   main()
   {
   int j, k;
   unsigned char buffer[82];
        printf("Enter 10 lines of data\n");
        for(j = 0;j < MAXL; ++j)
        {
             printf("Line: %d\n",j+1);
             if(!fgets(buffer,80,stdin))
                  break;
             line[j] = malloc(strlen(buffer)+1);
             strcpy(line[j],buffer);
        }

        printf("\n\nSort ten lines from stdin:\n");
        qsort(line,j,sizeof(unsigned char *),comp);

        for(k = 0;k < j; ++k)
        printf("Line: %d%s\n",k+1,line[k]);
   }


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