Insertion Operation
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.
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:
Step 1: TEMP = N-1POS = POS - 1Step 2: Repeat Step 3 while TEMP >= POSStep 3: A [TEMP+1] = A [TEMP]TEMP = TEMP - 1Step 2: A [POS] = XStep 1: N = N + 1
Program:
//Wirte program to perfrom Insertion of array element
#include <stdio.h>#include <conio.h>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; }}
Insertion Operation
Reviewed by Tech Specifier
on
May 09, 2020
Rating:
No comments: