In this article, we will see the code and explanation of logic part to insert
an element to a specified position in an array.
Let us look, variables used in this :
1) n is length of array.
2) pos is position where we need to insert the element x .
3) x is an element which we need to be insert at place pos.
Approach:
1. This approach firstly take elements for index 0 to pos-1 and then insert
element x at pos.
2. After this, rest of element is inserted in array.
Explanation of Logic Part:
1. Firstly, we need to create a new array let us say we create an
array named as newarr[] and size of this array should be one size
greater than previous arr[].
2. So, we will increase its size by newarr[n+1]. (n is length of
array)
3. Now, here comes for loop part.
4. int i will start from index 0 and it should be smaller than n+1.
(refer code)
5. then we can use if statement or if else if.
6. if (i<pos-1)
~ then we will insert
element of arr[i] in newarr[i]. This process gets repeated until
condition is true.
7. when previous condition turns false then next condition is
executed.
~if(i==pos-1)
~then, x will be inserted to newarr[i]. (x
is an element which we have to insert).
8. Similarly, when previous condition turns to be false, next if
statement is executed
~ if(newarr[i]=arr[i-1])
element of arr[i-1] is inserted to newarr[i]
(these are rest of elements after step 7).
9. Finally, we return newarr[].
import java.util.Arrays;
public class Insert_Element_in_array {
public static void main(String[] args) {
int arr[]={1,2,3,4,6,7,8,9};
int n = arr.length;
//we will call insert_element method
Insert_Element_in_array obj = new Insert_Element_in_array();
int x=5;
int pos=5;
//storing in arr[]
arr=insert_element(arr,x,pos);
System.out.println(Arrays.toString(arr));
}
static int[] insert_element(int arr[],int x,int pos)
{
//pos is where we need to insert element. It starts from 1
//x is an element which we have to insert in arr[]
//let us create a new array having size one more than arr[]
//we will give it name as newarr[]
// n is length of arr[]
int n = arr.length;
int newarr[]=new int[n+1];
for(int i=0;i<n+1; i++)
{
if(i<pos-1)
newarr[i]=arr[i];
if(i==pos-1)
newarr[i]=x;
if(i>pos-1)
newarr[i]=arr[i-1];
}
return newarr;
}
}