Selection sort¶
Content summary
This lesson introduces the selection sort algorithm.
Idea¶
Imagine you need to pick the best possible starting lineup from a group of players.
You do it like this: First, pick the best player. Then, from the remaining players, pick the second-best. Then the third-best, and so on.
Now apply this to an array.
If we treat "smallest" as "best", the strategy becomes: Find the smallest element and put it in the first position. Then find the next smallest and put it in the second position. Keep going until the array is fully sorted.
How the selection sort algorithm works
For each position i from the beginning of the array up to the second-to-last element:
- Scan the unsorted portion (from index
ito the end) to find the smallest element and remember its indexmin. - Swap
A[i]withA[min].
This process gradually builds the sorted part at the beginning of the array.
The main idea is illustrated below:
Example illustration¶
Flowchart¶
Visualization¶
Writing the program¶
1. Import the numpy library.
2. Write the function selection_sort() to implement the selection sort algorithm.
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 selection_sort() function to sort the array Array.
4. Run the program above. The output will be:
Source code¶
The complete code is available at:
Some English words¶
| Vietnamese | Tiếng Anh |
|---|---|
| hoán vị (hai phần tử) | swap |
| sắp xếp chọn | selection sort |
| so sánh | compare |