Linkin_Park

S&A lab 3 algorithms

Oct 29th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. struct qtys {
  2.     int comparisons;
  3.     int assignments;
  4. };
  5.  
  6.  
  7. void bubbleSort(vector <int> &array, int passesQty, qtys &_qtys) {
  8.     for (int i = array.size() - 1, j = 0; j != passesQty; i--, j++) {
  9.         for (int k = 0; k < i; k++) {
  10.             _qtys.comparisons++;
  11.  
  12.             if (array[k + 1] < array[k]) {
  13.                 int temp = array[k + 1];
  14.                 array[k + 1] = array[k];
  15.                 array[k] = temp;
  16.  
  17.                 _qtys.assignments += 3;
  18.             }
  19.         }
  20.     }
  21. }
  22.  
  23. void sortInterval (vector <int> &array, int limit, int l, int r, qtys &_qtys) {
  24.     if (r - l + 1 > limit) {
  25.         int pivot = array[(r + l) / 2],
  26.                 i = l,
  27.                 j = r;
  28.  
  29.         do {
  30.             _qtys.comparisons += 2;
  31.  
  32.             while (array[i] < pivot) {
  33.                 _qtys.comparisons++;
  34.                 i++;
  35.             }
  36.  
  37.             while (array[j] > pivot) {
  38.                 _qtys.comparisons++;
  39.                 j--;
  40.             }
  41.  
  42.             if (i <= j) {
  43.                 int temp = array[j];
  44.                 array[j] = array[i];
  45.                 array[i] = temp;
  46.                 i++;
  47.                 j--;
  48.                 _qtys.assignments += 3;
  49.             }
  50.         } while (i <= j);
  51.  
  52.         if (l < j) {
  53.             sortInterval(array, limit, l, j, _qtys);
  54.         }
  55.  
  56.         if (r > i) {
  57.             sortInterval(array, limit, i, r, _qtys);
  58.         }
  59.     }
  60. }
  61.  
  62. void quickSort(vector <int> &array, int limit, qtys &_qtys) {
  63.     sortInterval(array, limit, 0, array.size() - 1, _qtys);
  64.     bubbleSort(array, limit, _qtys);
  65. }
Advertisement
Add Comment
Please, Sign In to add comment