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

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz