Insert an element at a particular index in an array . Data structure Part-(3).#data #array

preview_player
Показать описание
Insert an element at a particular index in an array
Insert a given element at a specific position in an array.

Input
int arr[5] = {10, 20, 30, 40, 50}

Element = 100 position = 2.

Output
{10, 20, 100, 30, 40, 50}

Input
int arr[5] = {10, 20, 30, 40, 50}

Element = 100 index = -1 or 10.

Output
"Invalid Position"

Algorithm
1. Get the element value which needs to be inserted.

2. Get the position value.

3. Check whether the position value is valid or not.

4. If it is valid,

Shift all the elements from the last index to position index by 1 position to the right.

insert the new element in arr[position]

5. Otherwise,

Invalid Position

Visual Representation
Let's take an array of 5 integers.

1, 20, 5, 78, 30.

If we need to insert an element 100 at position 2, the execution will be,

Insert element in array
1. We need to insert element 100 at position 2.

2. Move all the elements from the last index(4) to the position(2) to one position right.

arr[4] (30) will be placed in arr[5].

arr[3] (78) will be placed in arr[4].

arr[2] (5) will be placed in arr[3].

3. Finally, the element 100 is placed at the position 2.
Рекомендации по теме