20-CS-122-001 Computer Science II Spring 2012
Use qsort on Cables Supplied by stdin

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

Prev      Next      Lectures      Source

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

typedef struct { int city1, city2, cost; } Cable;

int costCompare (const void *x, const void *y) {
   if ((*(Cable *)x).cost < (*(Cable *)y).cost) return -1;
   if ((*(Cable *)x).cost > (*(Cable *)y).cost) return 1;
   return 0;
}

#define MAX_SIZE 100

int main(int argc, char **argv) {
   int city1, city2, cost, count=0;
   Cable cables[MAX_SIZE];

   if (argc != 1) {  
      cout << "\nUsage: " << argv[0] << " < file\n"; 
      exit(0);  
   }

   while (cin >> city1 >> city2 >> cost) {
      if (count >= MAX_SIZE) {
	 cerr << "Array limits exceeded.\n";
	 exit (0);
      }
      cables[count].city1 = city1;
      cables[count].city2 = city2;
      cables[count++].cost = cost;
   }
   
   // Print the result 
   for (int i=0 ; i < count ; i++)
      cout << "[" << cables[i].city1 
	   << "-" << cables[i].city2
           << ":" << cables[i].cost
	   << "]\n";
   cout << "--------------------------\n";
   
   qsort(cables, count, sizeof(Cable), costCompare);
   
   // Print the result 
   for (int i=0 ; i < count ; i++)
      cout << "[" << cables[i].city1 
	   << "-" << cables[i].city2
           << ":" << cables[i].cost
	   << "]\n";
   cout << "\n";
}

// Sample output:
//  [0-1:10]
//  [0-2:14]
//  [0-3:11]
//  [0-4:8]
//  [1-2:9]
//  [1-3:20]
//  [1-4:18]
//  [2-3:12]
//  [2-4:16]
//  [3-4:5]
//  --------------------------
//  [3-4:5]
//  [0-4:8]
//  [1-2:9]
//  [0-1:10]
//  [0-3:11]
//  [2-3:12]
//  [0-2:14]
//  [2-4:16]
//  [1-4:18]
//  [1-3:20]