Inserting an element into array refers to the operation of adding another element to the array. This question usually asked in interviews to assess if candidate can effectively shift elements and insert new element.
While inserting an element into the array we assume that the size of array is large enough to hold the newly inserted element. For example, we have a 10-element linear array and suppose only 7 elements are in the array. In this case the array has 3 vacant positions and has space for new element for insertion.
On the other hand, if all 10 elements are already there in the array than array has no space; therefore insertion of new element will not take palce.
The following program inserts a data element item
into kth
position in a linear array lin_arr
of ARR_SIZE
10 with n
elements, where n
is less than ARR_SIZE
.
So, in order to insert data element in the given array we have to create space in lin_arr
by shifting all elements one position right from the kth
position. Here, the notable point is that we will start shifting elements in reverse order that is lin_arr[n]
, then lin_arr[n-1]
, ..., and last lin_arr[k]
. This is crux of insertion algorithm and interviewer asks this question to see how candidate starts shifting array elements to create space for the new element.
#include <stdio.h> #include <stdlib.h> #define ARR_SIZE 10 /* * lin_arr - linear array there we insert element * n - number of elements currently presesnt in array, must be less than equals to ARR_SIZE * k - position, where new elements will be inserted * item - data element that will be inserted */ void insertElement (int lin_arr[], int n, int k, int item) { // exit, if n or k is greater than ARR_SIZE if (n >= ARR_SIZE || k >= ARR_SIZE) exit(1); // exit, if n or k is negative if (n < 0 || k < 0) exit(1); //initialize j to last element int j = n; // loop until kth element while(j >= k) { //shift jth element right lin_arr[j] = lin_arr[j-1]; j--; } //insert item at k position lin_arr[k-1] = item; } int main() { int arr[ARR_SIZE] = {1, 2, 3, 4, 5, 6, 7, 0, 0, 0}; int i = 0; printf("Print array elements before inserting new item:\n"); for (i = 0; i < ARR_SIZE; i ++) printf("%d, ", arr[i]); printf("\n"); // insert 15 at position 3 in a 7-element array insertElement(arr, 7, 3, 15); printf("Print array elements after inserting new item:\n"); for (i = 0; i < ARR_SIZE; i++) printf("%d, ", arr[i]); printf("\n"); } OUTPUT ====== Print array elements before inserting new item: 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, Print array elements after inserting new item: 1, 2, 15, 3, 4, 5, 6, 7, 0, 0,
Share this page on WhatsApp