Advertisement
PikingFish

5.1

Oct 22nd, 2020
141
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int bubbleSort (int *arrayPointer, int size, bool (*f)(int, int), int *swapsPointer, int *comparesPointer)
  5. {
  6.     *swapsPointer = 0;
  7.     *comparesPointer = 0;
  8.    
  9.     for (int i = 0; i < size - 1; ++i)
  10.         for (int j = 0; j < size - i - 1; ++j)
  11.         {
  12.             if (f(*(arrayPointer + j), *(arrayPointer + j + 1) ) )
  13.             {
  14.                 int temp = *(arrayPointer + j);
  15.                 *(arrayPointer + j) = *(arrayPointer + j + 1);
  16.                 *(arrayPointer + j + 1) = temp;
  17.                
  18.                 ++*swapsPointer;
  19.             }
  20.            
  21.             ++*comparesPointer;
  22.         }
  23. }
  24.  
  25. bool ascending (int a, int b)
  26. {
  27.     return a > b;
  28. }
  29.  
  30. bool descending (int a, int b)
  31. {
  32.     return a < b;
  33. }
  34.  
  35. int main()
  36. {
  37.     int swaps;
  38.     int compares;
  39.     cout << "Array size = ";
  40.     int size;
  41.     cin >> size;
  42.     cout << endl;
  43.     int array[size];
  44.     int *arrayPointer = &array[0];
  45.     int *swapsPointer = &swaps;
  46.     int *comparesPointer = &compares;
  47.    
  48.     cout << "Array for ascending sort: ";
  49.     for(int i = 0; i < size; ++i)
  50.         cin >> array[i];
  51.    
  52.     bubbleSort(arrayPointer, size, ascending, swapsPointer, comparesPointer);  // Ascending sort and output
  53.     cout << "Ascending sort: ";
  54.     for(int i = 0; i < size; ++i)
  55.         cout << *(arrayPointer + i) << ' ';
  56.     cout << endl << "Swaps = " << swaps << ". Compares = " << compares << endl << endl;
  57.    
  58.     cout << "Array for descending sort: ";
  59.     for(int i = 0; i < size; ++i)
  60.         cin >> array[i];
  61.    
  62.     bubbleSort(arrayPointer, size, descending, swapsPointer, comparesPointer);  // Descending sort and output
  63.     cout << "Descending sort: ";
  64.     for(int i = 0; i < size; ++i)
  65.         cout << *(arrayPointer + i) << ' ';
  66.     cout << endl << "Swaps = " << swaps << ". Compares = " << compares;
  67.    
  68.     return 0;
  69. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement