How to Insert an element at a specific position in an Array in C++
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++. Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos. 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:
CPP
#include <iostream>
using namespace std;
int * insertX( int n, int arr[],
int x, int pos)
{
int i;
n++;
for (i = n; i >= pos; i--)
arr[i] = arr[i - 1];
arr[pos - 1] = x;
return arr;
}
int main()
{
int arr[100] = { 0 };
int i, x, pos, n = 10;
for (i = 0; i < 10; i++)
arr[i] = i + 1;
for (i = 0; i < n; i++)
cout << arr[i] << " " ;
cout << endl;
x = 50;
pos = 5;
insertX(n, arr, x, pos);
for (i = 0; i < n + 1; i++)
cout << arr[i] << " " ;
cout << endl;
return 0;
}
|
Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 50 5 6 7 8 9 10
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
21 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...