INSERTION SORT

//there is a simple program for sorting an array in increasing order by insertion sort

language=C++

#include<iostream>

using namespace std;

int main()
{
    int n;

    cin >> n;

    int a[n];

    for( int i = 0; i < n; i++ )

        cin >> a[i];

    for( int j = 1; j < n; j++ )
    {
        int key_value = a[j];
        int i = j-1;

        while( i >= 0 && a[i] > key_value )
        {

            a[i+1] = a[i];
            i = i-1;

        }

        a[i+1] = key_value;
    }

     for( int i = 0; i < n; i++ )

        cout << a[i] << " ";

     cout<<endl;

     return 0;
}

No comments:

Post a Comment

Kruskal Algorithm

Minimum Cost Spanning Tree By Kruskal Algorithm using priority_queue in c++ #include<bits/stdc++.h> using namespace std; typedef p...