Solutions to Selected Problems

Solutions for Column 1

1. This C program uses the Standard Library qsort to sort a file of integers.

int intcomp(int *x, int *y){   return *x - *y; }int a[1000000];int main(void){   int i, n=0;    while (scanf("%d", &a[n]) != EOF)        n++;    qsort(a, n, sizeof(int), intcomp);    for (i = 0; i < n; i++)        printf("%d\n", a[i]);    return 0;}

This C++ program uses the set container from the Standard Template Library for the same job.

int main(void){   set<int> S;    int i;    set<int>::iterator j;    while (cin >> i)        S.insert(i);    for (j = S.begin(); j != S.end(); ++j)        cout << *j << "\n";    return 0;}

Solution 3 sketches the performance ...

Get Programming Pearls, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.