Advertisement
yeskendir_sultanov

Insertion Sort

Mar 28th, 2024
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.50 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6.     int n;
  7.     cin >> n;
  8.     int a[n];
  9.     for (int i = 0; i < n; ++i) {
  10.         cin >> a[i];
  11.     }
  12.  
  13.     for (int i = 0; i < n; ++i) {
  14.         int j = i;
  15.         while (j > 0 && a[j - 1] > a[j]) {
  16.             swap(a[j - 1], a[j]);
  17.             --j;
  18.         }
  19.     }
  20.    
  21.     for (int i = 0; i < n; ++i) {
  22.         cout << a[i] << " ";
  23.     }
  24.    
  25.     return 0;
  26. }
  27. /*
  28. Time Complexity O(N^2)
  29. Memory Complexity O(1)
  30. */
  31.  
  32.  
  33.  
  34.  
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement