Skip to content

Commit 26209cb

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 9431399 commit 26209cb

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Section9ArrayAB/Array IMP/ArrayIMPCC.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,23 @@ public static void main (String[] args) {
3838
Step 3: i = 2 [2, 4, 6, 6, 8, 10] // Copy 6 to position 3
3939
4040
After insertion: [2, 4, 7, 6, 8, 10] // Place 7 at position 2
41+
42+
1. Loop iteration**: `i--`
43+
- Moves backward through the array
44+
- This backward movement is crucial to prevent overwriting data
45+
46+
Starting array: [2, 4, 6, 8, 10]
47+
i = 4: [2, 4, 6, 8, 10, 10] // Moved 10
48+
i = 3: [2, 4, 6, 8, 8, 10] // Moved 8
49+
i = 2: [2, 4, 6, 6, 8, 10] // Moved 6
50+
Result: [2, 4, 7, 6, 8, 10] // After inserting 7
51+
52+
The backward direction preserves data because:
53+
1. We start from the end, so we're always moving data into empty spots
54+
2. We never overwrite data before we've had a chance to move it
55+
3. Each element is moved exactly once to its new position
56+
57+
This is similar to moving books on a shelf:
58+
- If you need to make space in the middle, you start by moving the last book
59+
- Moving books from right to left ensures you always have space to move the next book
4160
*/

0 commit comments

Comments
 (0)