Sitemap

Data Structures and Algorithm_Arrays -2

Insertion in an array

2 min readSep 8, 2024

--

Source of background :Pinterest

Algorithm

INSERT (A,N,K,ITEM)

Get Mohana Priya.T’s stories in your inbox

Join Medium for free to get updates from this writer.

Where A represents the array into which we want to insert. N is the number of elements in that array. K is the position where we want to insert (positive integer less than equal to N) and ITEM is the thing to be inserted.

  1. Set I = N
  2. Repeat steps 3 and 4 while I≥ K
  3. Set A[ I+1] = A[I]
  4. Set I = (I — 1)
  5. Set A[K] = ITEM
  6. Set N = N+1
  7. Exit

Explanation

First we start from the back of the array. In the condition I ≥ K , we check all the numbers which are greater than the place where we want to insert out character. This checking occurs so that all the letters are shifted to one slot in the right to create an empty space to enter the new character. The condition A [I + 1] = A [I] does the same. Then once we reach Kth position, the item to be inserted is alloted into A[K] through the statement A[K] = ITEM.

The C code

// Insertion into Array 
#include <stdio.h>
int main() {
char A[5]= {'W','O','R','D','S'};
printf("%c%c%c%c%c \n",A[0],A[1],A[2],A[3],A[4]);
//Insert L after D
int i = 5;
int k = 3;
int n = 5;

while (i>=k)
{
A[i+1] = A[i];
i--;
}
A[k]='L';
n++;
printf("%c%c%c%c%c",A[0],A[1],A[2],A[3],A[4]);
return 0;
}

Output —

--

--

Mohana Priya.T
Mohana Priya.T

Written by Mohana Priya.T

MP. T is a blogger, student and a perpetual day dreamer 😊 Check out her STEM blogs at https://mohanapriyawrites.wixsite.com/newtonsapple