insertion sort

PHOTO EMBED

Thu May 22 2025 03:30:48 GMT+0000 (Coordinated Universal Time)

Saved by @RohitChanchar #c++

// You are using GCC
#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    for(int i=0;i<n;i++){
        int min=arr[i];
        int j=i-1;
        while(j>=0 && arr[j]>min){
            arr[j+1]=arr[j];
            j--;
        }
        arr[j+1]=min;
        // cout<<"iretation "<<i+1<<":";
        // for(int k=0;k<n;k++){
        //     cout<<arr[k]<<" ";
        // }
        // cout<<endl;
    }
    cout<<"after sorted using insertion sort:"<<endl;
    for(int i=0;i<n;i++){
        cout<<arr[i]<<" ";
    }
    
    return 0;
}
content_copyCOPY

This is a C++ implementation of insertion sort. In each iteration, the current element is compared with the elements before it and inserted into its correct position among the previously sorted elements. This process continues until the entire array is sorted. The code reads an array of size n, sorts it using insertion sort without using any built-in functions, and then prints the sorted array. The commented section can be used to view the array after each iteration for better understanding.