Advertisement
kirya_shkolnik

QuickSort

Dec 8th, 2020
243
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.  
  3. using namespace std;
  4. void quicksort(int arr[], int left, int right) {
  5.   int i = left, j = right;
  6.   int temp;
  7.   int sep = arr[(left + right) / 2];
  8.  
  9.   while (i <= j) {
  10.     while (arr[i] < sep)
  11.       i++;
  12.     while (arr[j] > sep)
  13.       j--;
  14.     if (i <= j) {
  15.       temp = arr[i];
  16.       arr[i] = arr[j];
  17.       arr[j] = temp;
  18.       i++;
  19.       j--;
  20.     }
  21.   };
  22.  
  23.  
  24.   if (left < j)
  25.     quicksort(arr, left, j);
  26.   if (i < right)
  27.     quicksort(arr, i, right);
  28.  
  29. }
  30. int main() {
  31.   int n;
  32.  
  33.  
  34.   cout << "Введите n - кол-во элементов массива\n";
  35.   cin >> n;
  36.    
  37.     if(n <= 0){
  38.       cout << "n - должно быть больше нуля";
  39.       return 0;
  40.   }
  41.   if(!cin){
  42.       cout << "error!";
  43.   }
  44.   int *arr = new int[n];
  45.   cout << "Введите целочисленные элементы массива: \n";
  46.   for (int i = 0; i < n; i++) {
  47.  
  48.     if(cin){
  49.     cout << "[" << i << "] = ";
  50.     int temp;
  51.     cin >> temp;
  52.     arr[i] = temp;
  53.     }
  54.     else {
  55.         cout << "Могут быть только целочисленные элементы";
  56.         return 0;
  57.     }
  58.   }
  59.  
  60.   quicksort(arr, 0, n-1);
  61.   cout << "Ответ: \n";
  62.   for (int i = 0; i < n; i++)
  63.     cout << arr[i] << " ";
  64.   return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement