20-CS-122-001 Computer Science II Spring 2012
Qsort: alternative version

Virtual functions, classes, inheritance, lists, queues, stacks, applications

   
// This version runs faster than the other version on smaller arrays
// if sort objects use only a small number (say 4) of bytes.  However,
// if sort objects use many bytes, then this version runs very slowly.
// For example, objects of the class of LongObject declared below use
// about 4000 bytes and the code below takes about 200 times longer to
// sort an array of 1000 such objects as the previous code takes to
// sort by moving pointers only.

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

// Simple class for testing purposes
class LongObject {
   long number[500];
   
 public:
   LongObject () { }
   long valueOf() { return number[0]; }
   void setValue(long n) { number[0] = n; }
};

// LOcompare:
//   Assume x and y are pointers to integers
//   Returns 0 if values are equal, -1 if *x < *y and, 1 if *x > *y
int LOcompare(const void *x, const void *y) {
   if (x == NULL || y == NULL) {
      cout << "Error: an object is NULL\n";
      exit (0);
   }

   if ((*(LongObject *)x).valueOf() <  (*(LongObject *)y).valueOf()) return -1;
   if ((*(LongObject *)x).valueOf() == (*(LongObject *)y).valueOf()) return 0;
   return 1;
}

#define SIZE 1000  // Sort 1000 LongObject objects

int main() {
   LongObject *b = new LongObject[SIZE];

   for (int i=0 ; i < SIZE ; i++)
      b[i].setValue((long)rand());

   qsort(b, SIZE, sizeof(LongObject), LOcompare);

   for (int i=0 ; i < SIZE ; i++)
      cout << b[i].valueOf() << "\n";
}