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, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.