20-CS-122-001 Computer Science II Spring 2012
Use qsort on an Array of Pointers

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

Prev      Next      Lectures      Source

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

typedef struct { int x; int y; int z; } Simple;

int cmp_x (const void *a, const void *b) {
   if ((**(Simple **)a).x < (**(Simple **)b).x) return -1;
   if ((**(Simple **)a).x > (**(Simple **)b).x) return 1;
   return 0;
}

int cmp_y (const void *a, const void *b) {
   if ((**(Simple **)a).y < (**(Simple **)b).y) return -1;
   if ((**(Simple **)a).y > (**(Simple **)b).y) return 1;
   return 0;
}

int cmp_z (const void *a, const void *b) {
   if ((**(Simple **)a).z < (**(Simple **)b).z) return -1;
   if ((**(Simple **)a).z > (**(Simple **)b).z) return 1;
   return 0;
}

int main () {
   Simple *s[4];
   for (int i=0 ; i < 4 ; i++) s[i] = new Simple;
   (*s[0]).x = 1; (*s[0]).y = 2; (*s[0]).z = 3;
   (*s[1]).x = 3; (*s[1]).y = 4; (*s[1]).z = 1;
   (*s[2]).x = 8; (*s[2]).y = 1; (*s[2]).z = 8;
   (*s[3]).x = 2; (*s[3]).y = 6; (*s[3]).z = 5;

   for (int i=0 ; i < 4 ; i++)
      cout << (*s[i]).x << " " << (*s[i]).y << " " << (*s[i]).z << "\n";
   cout << "=====================\n";

   qsort(s, 4, sizeof(Simple*), cmp_x);

   for (int i=0 ; i < 4 ; i++)
      cout << s[i]->x << " " << s[i]->y << " " << s[i]->z << "\n";
   cout << "---------------------\n";

   qsort(s, 4, sizeof(Simple*), cmp_y);

   for (int i=0 ; i < 4 ; i++)
      cout << s[i]->x << " " << s[i]->y << " " << s[i]->z << "\n";
   cout << "---------------------\n";

   qsort(s, 4, sizeof(Simple*), cmp_z);

   for (int i=0 ; i < 4 ; i++)
      cout << s[i]->x << " " << s[i]->y << " " << s[i]->z << "\n";
   cout << "---------------------\n";
}

// Sample output:
//  1 2 3
//  3 4 1
//  8 1 8
//  2 6 5
//  =====================
//  1 2 3
//  2 6 5
//  3 4 1
//  8 1 8
//  ---------------------
//  8 1 8
//  1 2 3
//  3 4 1
//  2 6 5
//  ---------------------
//  3 4 1
//  1 2 3
//  2 6 5
//  8 1 8
//  ---------------------