//insertion in a 1D sorted array
#include<iostream.h>
#include<conio.h>
main()
{
int a[50];
int i,n,k,flag=0,item;
cout<<"Enter No of elements in array";
cin>>n;
cout<<"Enter elements in accending";
for(i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<"Enter Element to Insert";
cin>>item;
for(i=1;i<=n;i++)
{
if(item<a[i])
{
for(k=n;k>=i;k--)
{a[k+1]=a[k];}
a[k+1]=item;
flag=1;
break;
}
}
if(flag!=1)
a[n+1]=item;
for(i=1;i<=n+1;i++)
cout<<a[i]<<endl;
getch();
}
#include<iostream.h>
#include<conio.h>
main()
{
int a[50];
int i,n,k,flag=0,item;
cout<<"Enter No of elements in array";
cin>>n;
cout<<"Enter elements in accending";
for(i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<"Enter Element to Insert";
cin>>item;
for(i=1;i<=n;i++)
{
if(item<a[i])
{
for(k=n;k>=i;k--)
{a[k+1]=a[k];}
a[k+1]=item;
flag=1;
break;
}
}
if(flag!=1)
a[n+1]=item;
for(i=1;i<=n+1;i++)
cout<<a[i]<<endl;
getch();
}
No comments:
Post a Comment