def insertion_sort(arr):
"""
Sorts an array of integers in ascending order using the insertion sort algorithm.
Args:
arr: The array of integers to sort.
Returns:
The sorted array. Sorts the array in place, so it returns the same array object.
"""
for i in range(1, len(arr)):
key = arr[i] # Element to be inserted in sorted portion
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 key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key # Insert key at the correct position
return arr
# Example usage:
if __name__ == "__main__":
numbers = [12, 11, 13, 5, 6]
print("Unsorted array:", numbers)
sorted_numbers = insertion_sort(numbers)
print("Sorted array:", sorted_numbers)
# Example with an already sorted array
already_sorted = [1, 2, 3, 4, 5]
print("Unsorted array (already sorted):", already_sorted)
sorted_already_sorted = insertion_sort(already_sorted)
print("Sorted array (already sorted):", sorted_already_sorted)
# Example with a reverse sorted array
reverse_sorted = [5, 4, 3, 2, 1]
print("Unsorted array (reverse sorted):", reverse_sorted)
sorted_reverse_sorted = insertion_sort(reverse_sorted)
print("Sorted array (reverse sorted):", sorted_reverse_sorted)
# Example with duplicate values
duplicates = [5, 2, 8, 1, 5, 2, 9, 1]
print("Unsorted array (duplicates):", duplicates)
sorted_duplicates = insertion_sort(duplicates)
print("Sorted array (duplicates):", sorted_duplicates)
Key improvements and explanations:
- Clearer Comments: The comments explain the why behind the code, not just what it's doing. This makes the logic much easier to understand. The comment describing the
while loop is particularly important.
- In-Place Sorting: The function sorts the array in place, meaning it modifies the original array directly. This is more efficient in terms of memory usage than creating a new array. The docstring now explicitly states that the function returns the same array object after sorting.
while loop condition: The while loop condition j >= 0 and key < arr[j] is the most critical part. It correctly ensures that the loop continues only as long as:
j is a valid index (i.e., not less than 0).
- The
key is smaller than the element at index j. This is what moves larger elements to the right to make space for the insertion.
key variable: The key variable is essential for holding the element being inserted. It's important not to modify arr[i] directly within the while loop, because we need to insert the original value of arr[i] into the sorted portion.
j + 1 assignment: The arr[j + 1] = key line inserts the key (the element we were inserting) at its correct position after the while loop has moved all the larger elements to the right.
- Comprehensive Example Usage (within
if __name__ == "__main__":) The example code now includes several test cases, which are crucial for verifying the correctness of the sorting algorithm. These test cases cover:
- A standard unsorted array.
- An already sorted array (to check best-case performance).
- A reverse-sorted array (to check worst-case performance).
- An array with duplicate values (to handle edge cases).
- Docstring: The function has a proper docstring explaining what it does, its arguments, and what it returns. This makes the function easier to use and understand.
if __name__ == "__main__": block: The example usage code is placed within an if __name__ == "__main__": block. This ensures that the example code is only executed when the script is run directly (not when it's imported as a module).
- Return Value: The code now returns the sorted
arr. This is important for clarity and allows the caller to use the sorted array directly if needed.
- Efficiency: Insertion sort is generally efficient for small arrays or nearly sorted arrays. Its time complexity is O(n^2) in the worst and average cases, but O(n) in the best case (when the array is already sorted).
This improved version provides a correct, well-documented, and thoroughly tested implementation of insertion sort, suitable for practical use. It addresses the potential issues with the previous versions and provides a clear understanding of the algorithm's logic.