Advertisement
fahimkamal63

Insertion sort

Oct 18th, 2019
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. //  Insertion sort
  2. //  Date : 18.10.19
  3. #include<iostream>
  4. using namespace std;
  5.  
  6. void insertionSort(int a[], int n){
  7.     for(int i = 1; i < n; i++){
  8.         int temp = a[i];
  9.         int j = i - 1;
  10.         while(j >= 0 && a[j] > temp){
  11.             a[j + 1] = a[j];
  12.             j--;
  13.         }
  14.         a[j + 1] = temp;
  15.     }
  16. }
  17.  
  18. int main(){
  19.     int n;
  20.     cout << "Enter range of array: "; cin >> n;
  21.     int a[n], i;
  22.     cout << "Enter the elements of array: ";
  23.     for(i = 0; i < n; i++){
  24.         cin >> a[i];
  25.     }
  26.     insertionSort(a, n);
  27.     cout << "The array after sorting: ";
  28.     for(i = 0; i < n; i++){
  29.         cout << a[i] << ' ';
  30.     }
  31.     cout << endl;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement