home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / magazine / pctchnqs / 1990 / number5 / bubbler.cpp < prev    next >
C/C++ Source or Header  |  1990-09-28  |  2KB  |  73 lines

  1. #include<stdlib.h>
  2. #include<stdio.h>
  3. #include<iostream.h>
  4. #include<iomanip.h>
  5.  
  6. const int ARRAY_SIZE = 100;
  7.  
  8. void swap(int &x, int &y);
  9. int  bubble_sort(int *target_array);
  10. void show_array(int *target_array);
  11.  
  12. void swap(int &x, int &y)
  13.  
  14. {
  15.   int temp;    // Define a local integer variable
  16.  
  17.   temp = x;    // Store x's value in temp
  18.   x = y;       // Copy y's value into x
  19.   y = temp;    // Copy x's value from temp into y
  20. }
  21.  
  22.  
  23. int  bubble_sort(int *target_array)
  24.  
  25. {
  26.   int sorted_flag = 1;
  27.   int i, pass_flag;
  28.  
  29.   do {
  30.     pass_flag = 1;
  31.     for (i=0; i < ARRAY_SIZE; i++)
  32.       if (target_array[i] > target_array[i+1])
  33.     {
  34.       swap(target_array[i],target_array[i+1]);
  35.       sorted_flag = 0;
  36.       pass_flag   = 0;
  37.     }
  38.   } while (pass_flag == 0);
  39.  
  40.   return sorted_flag;
  41. }
  42.  
  43. void show_array(int *target_array)
  44. {
  45.   int i,old_width;
  46.  
  47.   old_width = cout.width(5);
  48.   for (i=0; i<100; i++)
  49.     {
  50.       cout << setw(3) << target_array[i];
  51.       if ((i+1) % 20 == 0) cout << '\n';
  52.     }
  53.   cout << '\n';
  54.   cout.width(old_width);
  55. }
  56.  
  57. void main()
  58.  
  59. {
  60.   int i;
  61.   int test_array[ARRAY_SIZE];  // Declare an array of 100 integers
  62.  
  63.   for (i=0; i<100; i++)
  64.     test_array[i] = rand() % 100;
  65.   cout << "Here's the unsorted array:" << "\n";
  66.   show_array(test_array);
  67.   if (bubble_sort(test_array))
  68.     cout << "That array was already sorted!";
  69.   else
  70.     cout << "The sort of the array is complete.  Here it is: \n";
  71.     show_array(test_array);
  72.   cout << "\n";
  73. }