Deletion
8. Deletion in Array
Deletion in an array means removing an element from a specific position and then adjusting the remaining elements. Since arrays store elements in continuous memory, deletion requires shifting elements to maintain order.
1. What is Deletion in Array?
Deletion is the process of removing an element from an array at a given index and shifting the remaining elements to fill the empty space.
Example:
- Array: [10, 20, 30, 40, 50]
- Delete element at index 2
- Result: [10, 20, 40, 50]
2. Why Shifting is Required?
Arrays store elements in continuous memory locations. When an element is removed, a gap is created. To maintain continuity, all elements after the deleted position are shifted left.
3. Types of Deletion in Array
- Deletion from Beginning – Remove first element
- Deletion from Specific Position – Remove element at given index
- Deletion from End – Remove last element
4. Deletion from End
This is the simplest deletion operation.
1. Reduce array size by 1
2. Ignore last element
Example:
- Array: [10, 20, 30, 40]
- Delete last element
- Result: [10, 20, 30]
5. Deletion from Beginning
All elements are shifted left after removing the first element.
1. Start from index 1
2. Shift all elements to left
3. Reduce size
Example:
- Array: [10, 20, 30, 40]
- Delete first element
- Result: [20, 30, 40]
6. Deletion from Specific Position
This is the most common deletion operation in arrays.
1. Start from delete position
2. Shift elements left
3. Reduce size by 1
Example:
- Array: [10, 20, 30, 40, 50]
- Delete index 2
- Result: [10, 20, 40, 50]
7. Algorithm for Deletion
Step 2: Check valid position
Step 3: Shift elements left from position
Step 4: Decrease array size
Step 5: Stop
8. Time Complexity of Deletion
Time complexity depends on the position of deletion:
- From End: O(1)
- From Beginning: O(n)
- From Middle: O(n)
9. Advantages and Disadvantages
Advantages
- Simple to implement
- Direct index access
- Efficient for end deletion
Disadvantages
- Shifting required (costly)
- Time-consuming for large arrays
- Fixed size limitation