// librarySort.cc   Demo of the C library qsort routine
// P. Conrad for CISC220 06J

// NOTE: for details of the qsort library routine,
// use "man -s 3c qsort" on strauss

#include <cstdlib> // for qsort()
#include <cassert>

// the following routine comes directly from the "man -s 3c qsort" with
// comments added by P. Conrad

// It takes two pointers to integers (as void pointers) and 
// returns a number < 0 , equal to 0, or greater than 0 based on comparing
// them as integers.  
// (similar to what strcmp does with strings)

static int intcompare(const void *p1, const void *p2)
{
  // cast the pointers to integer pointers, then dereference them
  // to get the integer values pointed to

  int i = *((int *)p1);
  int j = *((int *)p2);

  // do a comparison, and return the appropriate value

  if (i > j)
    return (1);
  if (i < j)
    return (-1);
  return (0);

  // There is a temptation to suggest that we could
  // just return (i - j), but think about this... are there cases
  // where that would produce an erroneous result due to "wrap
  // around"...   e.g. i=-2000000000 (negative two billion), and
  // j = 1000000000 (positive one billion).  Subtract, and you get
  // negative three billion, except that in a 32 bit signed in, that
  // wraps around to a positive number

}

void sortArray(int a[], int n)
{
  qsort((void *)a, (size_t) n, sizeof (int), intcompare);
}




