20-CS-122-001 Computer Science II Spring 2012
Use qsort on a File of Random Cables

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;

// For qsort	
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;
}

int main(int argc, char **argv) {
   char buffer[1024];
   int count=0;

   // Print usage statement if number of command line arguments is wrong
   if (argc != 2) { 
      cout << "\nUsage: " << argv[0] << " \n";
      exit(0);  
   }

   // Count the number of lines (cables) in the file
   fstream fin(argv[1], ios::in);
   while (fin.getline(buffer, 1024)) count++;
   fin.close();

   // Allocate sufficient space
   Cable cables[count];

   // Open the file and copy the contents to the Cable array
   fstream gin(argv[1], ios::in);
   for (int i=0 ; i < count ; i++)
      gin >> cables[i].city1 >> cables[i].city2 >> cables[i].cost;
   gin.close();

   // Print the result 
   for (int i=0 ; i < count ; i++)
      cout << "[" << cables[i].city1 
           << "-" << cables[i].city2
           << ":" << cables[i].cost
	   << "]\n";
   cout << "--------------------------\n";

   // Sort all the Cables in cable in increasing order of cost  
   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]