20-CS-122-001 Computer Science II Spring 2012
Use qsort on an Array 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;

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 NCITIES 5

int main() {
int city1, city2, cost, count=0;
Cable cables[NCITIES*NCITIES];

for (int i=0 ; i < NCITIES-1 ; i++ ) {
for (int j=i+1 ; j < NCITIES ; j++) {
cables[count].city1 = i;
cables[count].city2 = j;
cables[count++].cost = rand() % 200;
}
}

// 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:183]
//  [0-2:86]
//  [0-3:177]
//  [0-4:115]
//  [1-2:193]
//  [1-3:135]
//  [1-4:186]
//  [2-3:92]
//  [2-4:49]
//  [3-4:21]
//  --------------------------
//  [3-4:21]
//  [2-4:49]
//  [0-2:86]
//  [2-3:92]
//  [0-4:115]
//  [1-3:135]
//  [0-3:177]
//  [0-1:183]
//  [1-4:186]
//  [1-2:193]
```