How to insert element in an array| data structure| part 2

 

C program to Insert an element in an Array







Data structure series 

Part 2


An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C.




Approach: 

Here’s how to do it.

 


First get the element to be inserted, say x

Then get the position at which this element is to be inserted, say pos

Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos.

Insert the element x now at the position pos, as this is now empty.

Below is the implementation of the above approach:

 


 
int main()
{
    int arr[100] = { 0 };
    int i, ele, pos,size;
 
 Printf("enter the size of array");
Scanf("%d",&size);

if(size<0||size>100){

Printf("enter size between 0 and 100");

}

else{

Printf("enter an element of the array");
    for (i = 0; i < size; i++)
        Scanf("%d",&arr[i]);
 
    Printf("your original array is ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
 
    Printf("enter an element to
be inserted");
Scanf("%d",&ele);
 
    Printf("enter the position at
Which you wanna insert
element");


Scanf("%d",&pos);
 
    
    Size++;
 
    if(pos>size||pos<0){

Printf("enter position according to size");

;
}

else{
    for (i = size-1; i >= pos; i--)
        arr[i+1] = arr[i];
 
    // insert x at pos
    arr[pos - 1] = ele;
 
    // print the updated array
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
}

 
    return 0;

}

 For above code time complexity is of order n-1.

For constant time complexity of order 1 which is the best way to insert element in unsorted array is as below:


 

#include <stdio.h>

 


int main()

{


    int arr[100] = { 0 };


    int i, ele, pos,size;

Printf("enter the size of an array");

Scanf("%d",&size);

If(size <0||size >100){

printf("enter size between 0 and 100");

}

else {

printf("enter an element of an array");

    for (i = 0; i < size; i++)


        Scanf("%d",&arr[i]);

 


    // print the original array


    for (i = 0; i < size; i++)


        printf("%d ", arr[i]);


    printf("\n");

    Printf("element to be inserted");

Scanf("%d",&ele);

Printf("position at which element to be                          inserted");

Scanf("%d",&pos);


   Size++;

 If (pos>size){

Printf("enter position according to the size");}

else{

arr[size]=arr[pos-1];

arr[pos -1]= ele;


    // print the updated array


    for (i = 0; i < size; i++)


        printf("%d ", arr[i]);


    printf("\n");

}

 }


    return 0;

}