INSERTION IN 1-D ARRAY
Write a C++ program to insert an element into a given
array in an appropriate position.
#include<iostream.h>
#include<process.h>
int findpos(int [],int,int);
void main()
{
int ar[50],item,n,index;
cout<<"How many elements do u want
to create array with ?(max.50)...";
cin>>n;
cout<<"\nEnter array elements(must
be sorted in ASC order)\n";
for(int i=0;i<n;i++)
cin>>ar[i];
char ch = 'y';
while(ch=='y'||ch=='Y')
{
cout<<"\nEnter element to be
inserted..";
cin>>item;
if(n==50)
{
cout<<"Overflow!!\n";
exit(1);
}
index=findpos(ar,n,item);
for(i=n;i>index;i--)
{
ar[i] = ar[i-1];
}
ar[index]=item;
n +=1;
cout<<"\n Want to insert more
elements ?(y/n)..";
cin>>ch;
}
cout<<"The array
now is as shown below..\n";
for(i=0;i<n;i++)
cout<<ar[i]<<" ";
cout<<endl;
}
int findpos(int ar[], int
size, int item)
{
int
pos;
if(item
< ar[0])
pos
= 0;
else
{
for(int
i=0; i<size-1; i++)
{
if(ar[i]
<=item && item < ar[i+1])
{
pos =
i+1;
break;
}
}
if(i ==
size-1)
pos =
size;
}
return pos;
}
No comments:
Post a Comment