Learning Insertion Sort: Principles and Code, Just Like Organizing Your Desktop

This article analogizes "sorting the desktop" to insertion sort, with the core idea being inserting elements one by one into their correct positions within the already sorted portion. The basic steps are: initializing the first element as sorted, starting from the second element, comparing it backward with the sorted portion to find the insertion position, shifting elements, and then inserting the current element. Taking the array `[5,3,8,2,4]` as an example: initially sorted as `[5]`, inserting 3 (after shifting 5) results in `[3,5]`; inserting 8 (directly appending) gives `[3,5,8]`; inserting 2 (shifting 8, 5, and 3 sequentially, then inserting at the beginning) yields `[2,3,5,8]`; inserting 4 (shifting 8 and 5, then inserting after 3) completes the sorting. The Python code implementation uses a double loop: the outer loop iterates over elements to be inserted, and the inner loop compares backward and shifts elements. It has a time complexity of O(n²), space complexity of O(1), and is suitable for small-scale data or nearly sorted data. It is an in-place sorting algorithm with no additional space required. This sorting analogy intuitively reflects the essence of "inserting one by one" and aids in understanding the sorting logic.

Read More