Sie sind auf Seite 1von 6

//INSERTION and DELETION from sorted array

#include<iostream.h>
#include<process.h>
int findpos(int[],int, int);
void insertar(int AR[],int & N);
void deletear(int AR[],int & N);
int Lsearch(int AR[],int size,int item)
{ for(int i=0;i<size;i++)
{ if (AR[i]==item) return i; }
return -1;
}

void main()
{
int AR[50],N,ITEM,INDEX,opt;
cout<<"Enter the array size::";
cin>>N;
cout<<"\nEnter array element(must be sorted in asc order)::";
for(int i=0;i<N;i++)
cin>>AR[i];
char ch='y';
while (ch=='y'|| ch=='Y')
{
cout<<"\n Menu";
cout<<"\n 1. INSERT ELEMENT IN THE ARRAY ";
cout<<"\n 2. DELETE ELEMENT FROM THE ARRAY";
cout<<"\n 3. EXIT";
cout<<"\n ENTER YOUR OPTION::";
cin>>opt;
switch(opt)
{
case 1: insertar(AR,N);
break;
case 2:deletear(AR,N);
break;
case 3: exit(0);
}
}
cout<"\n Do u Want to continue::";
cin>>ch;
}
void insertar(int AR[],int & N)
{
int element,index;
char ch='y';
do{ cout<<"\nEnter Element to be inserted..";
cin>>element;
if(N==50)
{ cout<<"Over flow!!\n"; exit(1); }
index=findpos(AR,N,element);
for(int i=N;i>index;i--)
{ AR[i]=AR[i-1]; }
AR[index]=element;
N+=1;
cout<<"\nWant to insert more element(y/n)";
cin>>ch;
}while(ch=='y' || ch=='Y');
cout<<"The array now is shown below..\n";
for(int i=0;i<N;i++)
cout<<AR[i]<<" ";
cout<<endl;
}
int findpos(int AR[],int size,int item)
{
int pos,i;
if(item<AR[0])
pos=0;
else
{ for(i=0;i<size-1;i++)
{ if(AR[i]<=item && item<AR[i+1])
pos=i+1;
}
}
if(item >AR[size-1])
{ pos=size; }
return pos;
}

void deletear(int AR[],int & N)


{
int element,index,i;
char ch='y';
do
{
cout<<"\nEnter element to be deleted..";
cin>>element;
if(N==0)
{ cout<<"Under flow!!\n"; exit(1); }
index=Lsearch(AR,N,element);
if(index!=-1)
AR[index]=0;
else
cout<<"Sorry!! No such element in the array.\n" ;
/* cout<<"\nThe array now is as shown below..\n";
cout<<"Zero(0) signifies deleted element\n";
for(i=0;i<N;i++)
cout<<AR[i]<<" ";
cout<<endl;
cout<<"After this emptied space will be shifted to the end of array ";*/
for(i=index;i<N;i++)
{
AR[i]=AR[i+1];
}
N-=1;
cout<<"\nWant to delete more elements?(y/n)";
cin>>ch;
}while(ch=='y' || ch=='Y');
cout<<"The array after shifting all emptied space toward right is..\n";
for(i=0;i<N;i++)
cout<<AR[i]<<" ";
}

Das könnte Ihnen auch gefallen