Insertion & Deletion Element in DSA

amannarayanm · October 05, 2021 · C
#include <stdio.h>
#include<stdlib.h>

void traversal(int arr[],int size)
{
    for(int i=0;i<size;i++)
    {
        printf("%d ",arr[i]);
    }
    printf("\n");
}
int findIndex(int arr[],int element,int size)
{
    for(int i=0;i<size;i++)
    {
        if(arr[i]==element)
        {
            return i;
            break;
        }
    }
    return -1;
}

int deletion(int arr[],int element,int size)
{
    int index = findIndex(arr,element,size);
    if(index==-1)
    {
        return -1;
    }
    else
    {
        for(int i=index;i<size;i++)
        {
            arr[i] = arr[i+1];
        }
    }
    return 1;
}
int insertion(int arr[],int element,int index,int size,int capacity)
{
    if(size>=capacity)
    {
        return -1;
    }
    else
    {
        for(int i=size-1;i>=index-1;i--)
        {
            arr[i+1] = arr[i];
        }
        arr[index] = element;
    }
    return 1;
}

int main() {
    int myarr[50] = {23,45,98,76,24};
    int element = 87;
    int size = 5;
    int index = 2;
    traversal(myarr,size);
    int res = insertion(myarr,element,index,size,50);
    if(res == -1){
        printf("Insertion is fail due to less Space in your Array");
    }
    else{
        printf("\nArray After Insertion of Element\n");
        size++;
        traversal(myarr,size);
    }
    int ans = deletion(myarr,element,size);
    if(ans == -1)
    {
        printf("%d is not in your Array",element);
    }
    else
    {
        printf("\nArray After Deletion of Element\n");
        size=size-1;
        traversal(myarr,size);
    }
    return 0;
}

Comments

Please sign up or log in to contribute to the discussion.