Insertion Operation in Array
Insertion operation is used to insert a new element at specific position in to one dimensional array.
In order to insert a new element into one dimensional array we have to create space for new element.
Suppose there are N elements in an array and we want to insert a new element between first and second element. We have to move last N-1 elements down in order to create space for the new element.
Algorithm For Insertion Operation in Array
Step 1: TEMP = N-1
POS = POS - 1
Step 2: Repeat Step 3 While TEMP ≥ POS
Step 3: A [TEMP+1] = A [TEMP]
TEMP = TEMP – 1
Step 4: A [POS] = X
Step 5: N = N + 1
Program For Insertion Operation in Array
#include<stdio.h>
#include<conio.h>
#define N 5
void main()
{
int a[N]={10,20,30,40,50};
int POS,x;
void traverse(int *a,int n);
void insert(int *a,int POS,int x);
clrscr();
printf("Before Insertion\n");
traverse(a,N);
printf("Enter Position:");
scanf("%d",&POS);
printf("Enter Value:");
scanf("%d",&x);
insert(a,POS,x);
printf("After Insertion\n");
traverse(a,N+1);
getch();
}
void insert(int *a,int POS,int x)
{
POS=POS-1;
int TEMP=N-1;
while(TEMP>=POS)
{
a[TEMP+1]=a[TEMP];
TEMP=TEMP-1;
}
a[POS]=x;
}
void traverse(int *a,int n)
{
int START=0;
while(START<n)
{
printf("%d\n",a[START]);
START=START+1;
}
}