Insertion sort¶
Content summary
This lesson introduces the insertion sort algorithm.
Overview¶
Review the general introduction to the sorting problem and sorting algorithms here.
Insertion sort algorithm¶
Idea¶
Imagine your class is lining up by height.
Now picture a student named Tèo. Everyone standing in front of Tèo who is taller than him steps one position back, making room. They keep moving back until they find someone shorter or equal to Tèo — then they stop. A gap appears exactly where Tèo should stand, and he slides into that spot.
This is exactly how insertion sort works: it repeatedly takes the next element and inserts it into its correct position among the elements that are already sorted.
Here’s the step-by-step process:
For each element A[i] from the second position (i = 1) to the end of the array:
- Save the current value
A[i]into a temporary variablet
(because the original spot will soon be overwritten).
-
Starting from position
j = i - 1, move backward through the sorted part:- As long as
A[j]is greater thant, shiftA[j]one position to the right (A[j + 1] = A[j]). -
Stop when:
- You reach the beginning of the array (
j < 0), or - You find an element
A[j]that is not greater thant(A[j] <= t).
- You reach the beginning of the array (
- As long as
-
Insert the saved value
tinto the gap that was created:A[j + 1] = t(After step 2 stops,
j + 1is exactly the correct position for the element.)
This way, after each iteration, the first i + 1 elements are always sorted — the sorted portion grows one element at a time, just like the line of students getting taller and taller from the front.
The main idea is illustrated below:
Example illustration¶
Flowchart¶
Visualization¶
Writing the program¶
1. Import the numpy library.
2. Write the function insertion_sort() to implement the insertion sort algorithm.
-
When the
whileloop stops,jpoints to the element that is smaller than or equal to the value being inserted (t).Therefore,
j + 1is the correct position where the originalA[i](saved int) should be inserted.
3. Write the main program.
In the main program, we will not ask the user to input the entire array. Instead, we create a fixed array in the code and then call the insertion_sort() function to sort the array Array.
4. Run the program above. The output will be:
Source code¶
The complete code is available at:
Summary mindmap¶
Some English words¶
| Vietnamese | Tiếng Anh |
|---|---|
| biến tạm thời | temporatory variable |
| hoán vị (hai phần tử) | swap |
| sắp xếp chèn | insertion sort |
| so sánh | compare |