Can anyone please explain me, step by step, each line of the following sorting algorithm which sorts the input lines numerically, if -n is given at the command line. (Program taken from the book "The C programming language, by brian kernighan and Dennis Ritchie" - Chapter 5. Section 5.11, page no.119)

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

#define MAXLINES 5000;
char *lineptr[MAXLINES};

int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);

void qsort(void *lineptr[], int left, int right, int (*comp)(void *, void *);
int numcmp(char *, char *);

main(int argc, char *argv[])
{
int nlines;
int numeric = 0;

if(argc > 1 && strcmp(argv[1],"-n") == 0)
numeric = 1;
if((nlines = readlines(lineptr, MAXLINES))>=0)
{
qsort((void **)lineptr, 0, nlines-1,(int (*)(void*, void*))(numeric ? numcmp : strcmp);
writelines(lineptr, nlines);
return 0;
}

else
{
printf("Input too short\n");
return 1;
}
}

what does this line mean..."qsort((void **)lineptr, 0, nlines-1,(int (*)(void*, void*))(numeric ? numcmp : strcmp);"

.
.
.

From man qsort:

SYNOPSIS
       #include <stdlib.h>

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


DESCRIPTION
       The  qsort()  function shall sort an array of nel objects, the initial
       element of which is pointed to by base. The size of  each  object,  in
       bytes, is specified by the width argument. If the nel argument has the
       value zero, the comparison function pointed to by compar shall not  be
       called and no rearrangement shall take place.

       The  application  shall ensure that the comparison function pointed to
       by compar does not alter the contents of the array.   The  implementa-
       tion may reorder elements of the array between calls to the comparison
       function, but shall not alter the contents of any individual  element.

So, the line you inquire about is passing a function to qsort based on the flags to the program. That function - in either case - will operate on the lineptr variable.
The numeric ? numcmp : strcmp portion of that simply decides whether to use a numeric sorting routine or a string sorting routine using a ternary operator. The (int (*)(void*, void*)) goop preceding that is just a cast to the appropriate type required by qsort (function accepting two void pointers returning an int).

As for what the code does step-by-step, I'd suggest you inject print statements into the code to see for yourself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.