Table of Contents
Insertion
7. Insertion in Array
Insertion in an array means adding a new element at a specific position in the array. Since arrays have a fixed size (in most languages), insertion requires shifting elements to create space.
1. What is Insertion in Array?
Insertion is the process of placing a new element at a given index in an array while maintaining the order of existing elements.
Core Idea: Insertion = Shift elements + Add new value at position
Example:
- Array: [10, 20, 30, 40]
- Insert 25 at index 2
- Result: [10, 20, 25, 30, 40]
2. Why Insertion Requires Shifting
Arrays store elements in continuous memory locations. So, when you insert an element in the middle, you must shift existing elements to the right.
Insertion is not direct replacement — it involves shifting elements to make space.
3. Types of Insertion in Array
- Insertion at Beginning – Add element at index 0
- Insertion at Specific Position – Add element at given index
- Insertion at End – Add element at last position
4. Insertion at the End
This is the simplest form of insertion.
Steps:
1. Place element at last index
2. Increase size by 1
1. Place element at last index
2. Increase size by 1
Example:
- Array: [10, 20, 30]
- Insert: 40
- Result: [10, 20, 30, 40]
5. Insertion at Beginning
All elements must be shifted to the right to create space at index 0.
Steps:
1. Shift all elements right by one position
2. Insert new element at index 0
1. Shift all elements right by one position
2. Insert new element at index 0
Example:
- Array: [10, 20, 30]
- Insert: 5
- Result: [5, 10, 20, 30]
6. Insertion at Specific Position
This is the most important type of insertion.
Steps:
1. Move elements from target index to right
2. Insert new element at that index
1. Move elements from target index to right
2. Insert new element at that index
Example:
- Array: [10, 20, 30, 40]
- Insert 25 at index 2
- Step 1: Shift 30 and 40 to right
- Step 2: Place 25 at index 2
- Result: [10, 20, 25, 30, 40]
7. Algorithm for Insertion
Step 1: Start
Step 2: Check if position is valid
Step 3: Shift elements to the right
Step 4: Insert new element
Step 5: Increase array size
Step 6: Stop
Step 2: Check if position is valid
Step 3: Shift elements to the right
Step 4: Insert new element
Step 5: Increase array size
Step 6: Stop
8. Time Complexity of Insertion
Time complexity depends on the position of insertion:
- At End: O(1)
- At Beginning: O(n)
- At Middle: O(n)
Worst case is O(n) because shifting elements is required.
9. Advantages and Disadvantages
Advantages
- Simple to implement
- Direct memory access
- Fast access using index
Disadvantages
- Shifting elements is costly
- Fixed size in static arrays
- Insertion is slow for large data
Final Insight
Insertion in arrays teaches an important concept in data structures:
Even simple operations can become costly when memory is continuous and fixed.