Insertion Sort in DSA C++

Program 1

// Implementation of Insertion Sort
#include<iostream>
using namespace std;
int main()
{
   int ar[500],n,i,j,k,temp;
   system("cls");
   cout<<"\n Enter limit: ";
   cin>>n;
   if(n<0 || n>500)
   cout<<"\n Invalid limit";
   else
   {
      cout<<"\n Enter "<< n<<"  elements: ";
      for(i=0;i<n;i++)
       cin>>ar[i];
       // insertion sort
        for(k=1;k<n;k++)
        {
             temp=ar[k];
             j=k-1;
             while(temp<ar[j] && j>=0)
             {
                  ar[j+1]=ar[j];
                  j--;
             }
             ar[j+1]=temp;
        }
        cout<<"\n Sorted elements: ";
        for(i=0;i<n;i++)
        cout<<"\n"<<ar[i];
   }
   return 0;
}

 

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *