C++ program to Insert an element Into sorted array

Insert an Element

Array is a collection of similar type of elements.We can perform operation on this.This program shows how to insert an element into sorted array.

  • In this program we first have taken the size of array.
  • After taking the size of array user will enter the elements into array.
  • After entering the element the program will sort the array in ascending order.
  • Once the sorting will be done user will enter the location where he/she wants to insert the element.
  • At last after entering the location program will ask you to enter a element you want to insert.
  • At the end you will get a output of new array.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
 int x[100],y,j,i,z,v,q,s;
 cout<<"Enter size of array:- ";
 cin>>y;
 cout<<"Enter Elements in array:- \n";
 for(i=0;i<y;i++)
 {
  cin>>x[i];
 }
 for(i=0;i<y;i++)
  {
     for(j=i+1;j<y;j++)
      {
       if(x[i]>x[j])
	{
	 v=x[j];
	 x[j]=x[i];
	 x[i]=v;
	}
      }
  }
 cout<<"Sorted array is:- \n";
 for(i=0;i<y;i++)
  {
   cout<<x[i]<<endl;
  }

  cout<<"Enter Location you want to insert:-";
  cin>>s;
  cout<<"Enter Number:- ";
  cin>>q;
  for(i=y;i>=s;i--)
    {
     x[i]=x[i-1];
    }
    y++;
    x[s-1]=q;

    for(i=0;i<y;i++)
     {
      cout<<x[i]<<endl;
     }

 getch();
}

OUTPUT:-

Before Insert

insert An element

After Insert

insert an element

Leave a Reply

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