inhuman_Arif

Ascending order using insertion sort

Oct 28th, 2021
587
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. typedef long long ll;
  5.  
  6. int main()
  7. {
  8.     #ifndef ONLINE_JUDGE
  9.         freopen("input.txt", "r", stdin);
  10.         freopen("output.txt", "w", stdout);
  11.     #endif
  12.  
  13.     int n;
  14.     cin >> n;
  15.     int arr[n];
  16.     for(int i=0;i<n;i++)
  17.         cin >> arr[i];
  18.     for (int i = 1; i < n; i++)
  19.     {
  20.         int key = arr[i];
  21.         int j = i - 1;
  22.         while (j >= 0 && arr[j] > key)
  23.         {
  24.             arr[j + 1] = arr[j];
  25.             j = j - 1;
  26.         }
  27.         arr[j + 1] = key;
  28.     }
  29.     for(int i=0;i<n;i++)
  30.         cout << arr[i] << " ";
  31.     cout << endl;
  32.    
  33.     return 0;
  34. }
RAW Paste Data