Inserting an element in an Array at Any Position
Arrays are fixed-size data structures that can contain only homogeneous elements. Inserting an element in an array is one of the basic operations done in an array.
To insert an element at the end of an array is easy we can directly insert the element at the end index of an array. Inserting in other positions would elements that are before their position to be shifted to the right. To make space for the element to be inserted.
To shift the elements, we can traverse the array from the end to the position minus one where we want to insert and shift the elements
for(int i = n-1; i > pos-1; i--){
arr[i] = arr[i-1];
}
Finally, insert the element at the specified position.
arr[pos-1] = k;
The final method would look as below.
public static int[] insertatAnyPos(int arr[], int k, int pos)
{
int n = arr.length;
for(int i = n-1; i > pos-1; i--)
{
arr[i] = arr[i-1];
}
arr[pos-1] = k;
return arr;
}
Subscribe to my newsletter
Read articles from Pranjit Medhi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by