Programming Examples
Cpp program to insert any number in a sorted array using function
Write a cpp program to insert any number in a sorted array while maintaining the order using functionÂ
Solution
#include<iostream>
using namespace std;
int INSRT(int[],int,int);
int main(){
int arr[50],N,i,pos,ITEM,index;
cout<<"Enter the desired array size "<<endl;
cin>>N;
cout<<"Enter the elements(Sorted in ascending order) "<<endl;
for(i=0;i<N;i++)
{
cin>>arr[i];
}
cout<<"Enter the number which needs to be inserted";
cin>>ITEM;
index=INSRT(arr,N,ITEM);
if(N==50)
{
cout<<"Overflow!!";
exit(1);
}
cout<<"Index is:"<<index<<endl;
for(i=N;i>index;i--)
{
arr[i]=arr[i-1];
}
arr[index]=ITEM;
N+=1;
for(i=0;i<N;i++)
{
cout<<arr[i]<<" ";
}
}
int INSRT(int arr[],int size, int num)
{
int pos;
//finding position of that number
for(int i=0;i<size;i++)
{
if(num<arr[0])
{
pos=0;
break;
}
else if(arr[i]<=num && arr[i+1]>num)
{
pos=i+1;
break;
}
else
{
pos=size-1;
}
}
return pos;
}
Output
Enter the desired array sizeÂ
5
Enter the elements(Sorted in ascending order)Â
2
4
6
8
10
Enter the number which needs to be inserted 7
Index is:3
2 4 6 7 8 10