Advertisement
jasonpogi1669

Odd-Even Sort using C++

Aug 26th, 2021
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void OddEvenSort(int a[], int n) {
  6.     bool is_sorted = false;
  7.     while (!is_sorted) {
  8.         is_sorted = true;
  9.         // even-positions
  10.         for (int i = 0; i + 1 < n; i += 2) {
  11.             if (a[i] > a[i + 1]) {
  12.                 swap(a[i], a[i + 1]);
  13.                 is_sorted = false;
  14.             }
  15.         }
  16.         // odd positions
  17.         for (int i = 1; i + 1 < n; i += 2) {
  18.             if (a[i] > a[i + 1]) {
  19.                 swap(a[i], a[i + 1]);
  20.                 is_sorted = false;
  21.             }
  22.         }
  23.     }
  24. }
  25.  
  26. int main() {
  27.     ios::sync_with_stdio(false);
  28.     cin.tie(0);
  29.     int n;
  30.     cin >> n;
  31.     int a[n];
  32.     for (int i = 0; i < n; i++) {
  33.         cin >> a[i];
  34.     }
  35.     OddEvenSort(a, n);
  36.     for (int i = 0; i < n; i++) {
  37.         cout << a[i] << " ";
  38.     }
  39.     cout << '\n';
  40.     return 0;
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement