Insert an Element in the Middle of an Array
☰Fullscreen
Table of Content:
In Java, inserting an element in the middle of an array involves a few steps. Since arrays have a fixed size, you can't directly insert an element without creating a new array with a larger size. Here’s how you can do it:
Steps to Insert an Element in the Middle of an Array
- Create a new array with a size that is one greater than the original array.
- Copy the elements from the original array to the new array, stopping at the index where you want to insert the new element.
- Insert the new element at the desired index.
- Copy the remaining elements from the original array to the new array.
Example Code
Here’s a complete Java program demonstrating how to insert an element in the middle of an array:
public class InsertInMiddleArray { public static void main(String[] args) { // Original array int[] originalArray = {10, 20, 30, 40, 50}; int elementToInsert = 25; // Element to insert int position = 2; // Index at which to insert (middle) // Call the method to insert the element int[] newArray = insertInMiddle(originalArray, elementToInsert, position); // Print the new array System.out.println("New array after insertion:"); for (int num : newArray) { System.out.print(num + " "); } } public static int[] insertInMiddle(int[] array, int element, int position) { // Create a new array with size one greater than the original int[] newArray = new int[array.length + 1]; // Copy elements from the original array to the new array for (int i = 0; i < position; i++) { newArray[i] = array[i]; } // Insert the new element at the specified position newArray[position] = element; // Copy the remaining elements from the original array for (int i = position + 1; i < newArray.length; i++) { newArray[i] = array[i - 1]; // Shift elements to the right } return newArray; // Return the new array } }
Explanation of the Code
- Original Array: We start with an array containing some initial elements.
- Insert Method: The
insertInMiddle
method takes the original array, the element to insert, and the position where the element should be inserted. - New Array Creation: We create a new array that is one element larger than the original array.
- Copying Elements: We use a loop to copy elements before the insertion point and then place the new element at the specified position.
- Remaining Elements: We copy the remaining elements from the original array, adjusting the index since we have inserted a new element.
- Output: Finally, we print the new array to confirm that the element was inserted correctly.
Output
When you run the program, you will get the following output:
New array after insertion: 10 20 25 30 40 50
This shows that the element 25
was successfully inserted in the middle of the original array.