Shiyan12

Пузырёк

Dec 22nd, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. #include <iostream>
  2. #include <ctime>
  3.  
  4. using namespace std;
  5.  
  6. void swap(int &a, int &b) {
  7.     int k = a;
  8.     a = b;
  9.     b = k;
  10. }
  11.  
  12. // СОРТИРОВКА МЕТОДОМ ПУЗЫРЬКА
  13. void bubble(int *& a) {
  14.     bool f = true;
  15.     for (int i = N; i > 0 && f; i--) {
  16.         f = false;
  17.         for (int j = 0; j < i - 1; j++)
  18.             if (a[j] > a[j + 1]) {
  19.                 swap(a[j], a[j+1]);
  20.                 f = true;
  21.             }
  22.     }
  23. }
  24.  
  25. int main() {
  26.     setlocale(LC_ALL, "rus");
  27.     int N;
  28.     cout << "N = ";
  29.     cin >> N;
  30.     int * a = new int[N];
  31.    
  32.     srand(time(0));
  33.     cout << "Изначальный массив ";
  34.     for (int i = 0; i < N; i++) {
  35.         a[i] = rand() % 21 - 10;
  36.         cout << a[i] << " ";
  37.     }
  38.  
  39.     bubble(a);
  40.  
  41.     cout << endl;
  42.     cout << "Отсортированный массив ";
  43.  
  44.     for (int i = 0; i < N; i++)
  45.         cout << a[i] << " ";
  46.    
  47.     delete[] a;
  48.     return 0;
  49. }
Add Comment
Please, Sign In to add comment