Sorting things using qsort

Sorting things using qsort

/* 
   An example showing the use of the "qsort" function for
   sorting 100 random numbers.

   Michael Ashley / UNSW / 11-Apr-2003
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <assert.h>

int myComparisonFunction(const void *x, const void *y) {

    // x and y are pointers to doubles.

    // Returns -1 if x < y
    //          0 if x == y
    //         +1 if x > y

    double dx, dy;

    dx = *(double *)x;
    dy = *(double *)y;

    if (dx < dy) {
        return -1;
    } else if (dx > dy) {
        return +1;
    }
    return 0;
}

int main(void) {
    struct timeval t;
    double data[100];
    int i;

    // Obtain the time of day, to microsecond resolution.

    assert(0 == gettimeofday(&t, NULL)); 

    // Use the number of microseconds as the seed for the system
    // random number generator.

    srandom(t.tv_usec);
  
    // Generate 100 random numbers between 0.0 and 1.0.

    for (i = 0; i < ((sizeof data) / (sizeof data[0])); i++) {
        data[i] = random()/((double) RAND_MAX);
    }

    // Now sort them into ascending order.

    qsort(data, (sizeof data) / (sizeof data[0]), sizeof data[0],
	  &myComparisonFunction);

    // And print them out.

    for (i = 0; i < ((sizeof data) / (sizeof data[0])); i++) {
        printf ("data[%d] = %f\n", i, data[i]);
    }
    
    return 0;
}

And here is a really tricky example showing how to sort character strings.

/* 
   An example showing the use of the "qsort" function for
   sorting up to 100 character strings. 

   Michael Ashley / UNSW / 11-Apr-2003
*/

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

int myComparisonFunction(const void *x, const void *y) {

    // This is a wrapper for the "strcmp" function.

    // x and y are pointers to pointers to character strings

    // Returns -1 if x < y
    //          0 if x == y
    //         +1 if x > y

  return (strcmp(*(const char **)x, *(const char **)y));

}

int main(void) {
    char *data[100];
    char *p;
    int i, numStrings;

    // Read up to 100 character strings from standard input.

    for (i = 0; i < ((sizeof data) / (sizeof data[0])); i++) {
        if (1 != scanf("%as", &data[i])) {
	    break;
        }
    }

    numStrings = i;

    printf ("%d strings found\n", numStrings);

    // Sort them alphabetically.

    qsort(data, numStrings, sizeof data[0],
	  &myComparisonFunction);

    // Print them out, and free the memory malloc'ed by scanf.

    for (i = 0; i < numStrings; i++) {
        printf("data[%d] = \"%s\"\n", i, data[i]);
        free(data[i]);
    }
    
    return 0;
}