To implement insertion sort on an array of integers in Python, we can follow the standard approach where the array is sorted in-place. Insertion sort is a simple, comparison-based sorting algorithm that builds the final sorted array one item at a time. It's particularly efficient for small data sets or nearly sorted arrays.
🧠 Key Idea of Insertion Sort
- Start from the second element (index
1).
- Consider the current element as the "key".
- Compare this key with the previous elements (to the left of the key).
- Shift all larger elements one position to the right to make space for the key.
- Insert the key into its correct position in the sorted subarray.
This process is repeated for each element from index 1 to the end of the array.
✅ Python Implementation
def insertion_sort(arr):
"""
Sorts the input list 'arr' in ascending order using the insertion sort algorithm.
Parameters:
arr (list): A list of integers to be sorted in-place.
"""
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i - 1
# Move elements of arr[0..i-1], that are greater than key,
# to one position ahead of their current position
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
# Insert the key into its correct position
arr[j + 1] = key
📌 Example Usage
# Example array
arr = [5, 2, 4, 6, 1, 3]
# Apply insertion sort
insertion_sort(arr)
# Output the sorted array
print(arr) # Output: [1, 2, 3, 4, 5, 6]
🧪 Edge Cases Handled
- Empty list: No error, loop doesn't execute.
- Single-element list: Already sorted.
- Already sorted list: Inner loop doesn't run, resulting in O(n) best-case time.
- Reverse-sorted list: Worst-case scenario, O(n²) time.
- Duplicate elements: Maintains relative order (stable sort).
⏱️ Time Complexity
- Best Case (O(n)): When the array is already sorted.
- Worst Case (O(n²)): When the array is reverse sorted.
- Average Case (O(n²)): For random data.
📝 Notes
- This implementation sorts the list in-place, meaning it modifies the original list.
- If you want to avoid modifying the original list, you can create a copy before sorting.
- Insertion sort is stable and adaptive, making it suitable for small or nearly sorted arrays.
🔄 Optional: Returning a New Sorted List
If you prefer to return a new sorted list instead of modifying the original:
def insertion_sort(arr):
arr = arr.copy()
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
This implementation ensures that the original list remains unchanged, and a new sorted list is returned.