20-CS-122-001 Computer Science II Spring 2012
Sort an Arrays of Objects

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

Prev      Next      Lectures      Source      Another Version          Man page on qsort

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

// Simple class for testing purposes
class LongObject {
   long number;
   
 public:
   LongObject (long n) { number = n; }
   long valueOf() { return number; }
};

// Compfunc:
//   Assume x and y are pointers to LongObject objects (see below)
//   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 30  // Sort 30 LongObject objects

int main() {
   
   LongObject *object_array[SIZE];

   for (int i=0 ; i < SIZE ; i++)
      object_array[i] = new LongObject((long)rand());

   qsort(object_array, SIZE, sizeof(LongObject *), LOcompare);

   for (int i=0 ; i < SIZE ; i++)
      cout << object_array[i]->valueOf() << "\n";
}