home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / FBUBBLE.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  2KB  |  66 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. #include <stdlib.h>
  7. #include <generic.h>
  8. #include <iostream.h>
  9. #include <string.h>
  10.  
  11. #define LocalScope(function) struct name3(function,Local,Scope) { public
  12. #define EndLocalScope } local
  13.  
  14. void BubbleSort(int n, char *records[], char *keys[])
  15. {
  16.     // Bubble Sort from Knuth, Vol. 3
  17.     LocalScope(BubbleSort):
  18.         int bound, t;
  19.         void CompareExchange(int j, char *records[], char *keys[]) {
  20.             if (::strcmp(keys[j], keys[j+1]) > 0) {
  21.                 char *temp = records[j];
  22.                 records[j] = records[j+1];
  23.                 records[j+1] = temp;
  24.                 temp = keys[j];
  25.                 keys[j] = keys[j+1];
  26.                 keys[j+1] = temp;
  27.                 t = j;
  28.             }
  29.         }
  30.     EndLocalScope;
  31.  
  32.     local.bound = n;
  33.     do {
  34.         local.t = -1;
  35.         for (int j = 0; j < local.bound-1; j++) {
  36.             local.CompareExchange(j, records, keys);
  37.         }
  38.         local.bound = local.t + 1;
  39.     } while (local.t != -1);
  40. }
  41.  
  42. char *records[] = {
  43.     "Stroustrup, Bjarne",
  44.     "Lippman, Stan",
  45.     "Hansen, Tony",
  46.     "Koenig, Andrew"
  47. };
  48.  
  49. char *keys[] = {
  50.     "bs",
  51.     "stan",
  52.     "hansen",
  53.     "ark"
  54. };
  55.  
  56. void main() {
  57.     for (int i = 0; i < 4; i++) {
  58.         cout << records[i] << "\t" << keys[i] << endl;
  59.     }
  60.     BubbleSort(4, records, keys);
  61.     cout << endl;
  62.     for (i = 0; i < 4; i++) {
  63.         cout << records[i] <<  "\t" << keys[i] <<endl;
  64.     }
  65. }
  66.