Skip to content

Commit 9431399

Browse files
committed
feat: Implement insertion in an array by shifting elements to the right
🧠 Logic: - Initializes an integer array and inserts a new element at a specific index. - Elements from the insertion point onward are shifted one position to the right. - The new element is placed at the desired index. - Demonstrates a classic array insertion algorithm with manual element shifting. Signed-off-by: Somesh diwan <[email protected]>
1 parent dd20658 commit 9431399

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed
Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
class ArrayIMPCC
2-
{
3-
public static void main (String[] args)
4-
{
1+
class ArrayIMPCC {
2+
public static void main (String[] args) {
53
int []array = new int[100];
64
array[0] = 2;
75
array[1] = 4;
@@ -14,20 +12,30 @@ public static void main (String[] args)
1412
int newElement = 7; // Element to be inserted
1513

1614
// Shift elements to make space for the new element
17-
for (int i = size - 1; i >= newPosition; i--)
18-
{
15+
for (int i = size - 1; i >= newPosition; i--) {
1916
array[i + 1] = array[i];
17+
//array insertion algorithm that shifts elements to the right to make space for a new element.
2018
}
2119

2220
// Insert the new element at the specified position
2321
array[newPosition] = newElement;
24-
2522
size++; // Update the size of the array
2623

27-
// Print the updated array
24+
System.out.println("Array after insertion: ");
2825
for (int i = 0; i < size; i++) {
2926
System.out.print(array[i] + " ");
3027
}
31-
3228
}
3329
}
30+
31+
/*
32+
Initial array: [2, 4, 6, 8, 10]
33+
34+
insert 7 here (at index 2)
35+
36+
Step 1: i = 4 [2, 4, 6, 8, 10, 10] // Copy 10 to position 5
37+
Step 2: i = 3 [2, 4, 6, 8, 8, 10] // Copy 8 to position 4
38+
Step 3: i = 2 [2, 4, 6, 6, 8, 10] // Copy 6 to position 3
39+
40+
After insertion: [2, 4, 7, 6, 8, 10] // Place 7 at position 2
41+
*/

0 commit comments

Comments
 (0)