Insertion sort algorithm implementation using CPP language



/*Md. Alamgir Hossain
 Dept. of Computer Science & Engineering.
Jessore University of Science & Technology.
 */
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int arr[100];
    int n;
    cout<<"Enter how many numbers you want to sort : "<<endl;
    cin>>n;

    cout<<"Enter "<<n<<" numbers : ";
    for(int i=0;i<n;i++){

        cin>>arr[i];
    }

    for(int j=1;j<n;j++){
        int k=j;

        while(k>0&&arr[k-1]>arr[k]){
            int value = arr[k];
            arr[k] = arr[k-1];
            arr[k-1] = value;
            k--;
        }
    }

    cout<<"Sorted array is : \n\n";
    for(int i=0;i<n;i++){
        cout<<arr[i]<<"\t";
    }

    cout<<"\n\n";
    return 0;
}

///Cpmplexity : o(n^2) && o(n)

No comments:

Post a Comment