Vla_DOS

quickSort

May 6th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <conio.h>
  3. #include <time.h>
  4. using namespace std;
  5.  
  6. int cheng = 0, simile = 0;
  7. void quickSort(int arr[], int left, int right) {
  8.     int i = left, j = right;
  9.     int tmp;
  10.     int pivot = arr[(left + right) / 2];
  11.     /* partition */
  12.     while (i <= j) {
  13.         while (arr[i] < pivot)
  14.             i++;
  15.         while (arr[j] > pivot)
  16.             j--;
  17.         cheng++;
  18.         if (i <= j) {
  19.             simile++;
  20.             tmp = arr[i];
  21.             arr[i] = arr[j];
  22.             arr[j] = tmp;
  23.             i++;
  24.             j--;
  25.         }
  26.     };
  27.     /* recursion */
  28.     if (left < j)
  29.         quickSort(arr, left, j);
  30.     if (i < right)
  31.         quickSort(arr, i, right);
  32. }
  33. int main() {
  34.     setlocale(LC_CTYPE, "Russian");
  35.     int num;
  36.     cout << "Колво элементов: ";
  37.     cin >> num;
  38.  
  39.     int* mass = new int[num];
  40.     for (int i = 0; i < num; i++) {
  41.         mass[i] = rand() % 20 + 100;
  42.         cout << mass[i] << " ";
  43.     }
  44.     cout << endl;
  45.     cout << "Quicksorted array:" << endl;
  46.     quickSort(mass, 0, num - 1);//функция квиксорта.
  47.     for (int i = 0; i < num; i++) {
  48.         cout << mass[i] << "\t";
  49.     }
  50.     cout << endl;
  51.     cout << cheng << endl;
  52.     cout << simile << endl;
  53.  
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment