Insertion Sort is a simple and intuitive sorting algorithm that works by comparing each element in a list with the elements that come before it, and inserting it in its correct position within the sorted part of the list. It is similar to how we arrange playing cards in our hand when playing a card game.
-
Concept: Imagine you have a list of numbers that you want to sort in ascending order. The algorithm works by maintaining a "sorted portion" of the list and an "unsorted portion". Initially, the sorted portion contains only the first element, and the unsorted portion contains the rest of the list.
-
Iteration: The algorithm iterates through the unsorted portion of the list, starting from the second element. For each element, it compares the current element with the elements in the sorted portion (from right to left) to find the correct position to insert the current element.
-
Comparison and Insertion: If the current element is smaller than an element in the sorted portion, it means that the current element should be inserted before that element. The elements in the sorted portion that are larger than the current element are shifted one position to the right, making space for the current element to be inserted in its correct position.
-
Progress: The algorithm continues comparing and inserting elements until it reaches the end of the list. At this point, the entire list is sorted.
-
Efficiency: The Insertion Sort algorithm has a time complexity of O(n^2) in the worst and average cases, which makes it inefficient for large datasets. However, it performs well for small or partially sorted datasets and is easy to understand and implement.
Consider this list of numbers: [5, 3, 8, 4, 2]
- The first element,
5
, is considered sorted. - Compare
3
with5
. Since3
is smaller, move5
to the right and insert3
before5
. The list becomes:[3, 5, 8, 4, 2]
8
is already larger than all elements in the sorted portion, so no change is needed:[3, 5, 8, 4, 2]
- Compare
4
with8
,5
, and3
. Insert4
between3
and5
. The list becomes:[3, 4, 5, 8, 2]
- Compare
2
with8
,5
,4
, and3
. Insert2
before3
. The list becomes:[2, 3, 4, 5, 8]
The final sorted list is [2, 3, 4, 5, 8]
.