Algorithms and Data Structures in Python: Selection Sort

Yue
2 min readSep 2, 2020

Introduction

We’ve discussed Bubble Sort in the previous post, now let’s go to another basic sorting algorithm: Selection Sort.

Similar to bubble sort, selection sort rearranged each element but instead of let larger element merge to the top (end of the array), it stacks smaller element to the bottom (head of the array)

Implementation of Selection Sort in Python

As shown in the code snippet above, selection sort also runs in a nested-loop base where in the outer loop, the algorithm iterate through the target array and keep the index of lowest element. Within the inner loop, this function go through each element starting from index i+1 and find the lowest element, if a new lowest element is found, the “lowest” variable is updated and set to the new value.

After each inner loop is done, we simply swap the lowest element and the head of this portion of array (arr[i]).

Let’s review the printed result as shown below:

-----iteration:0-----
The index of current smallest number is: 0
1 is smaller than 4
Update lowest value to 1
-----iteration:1-----
The index of current smallest number is: 1
2 is smaller than 4
Update lowest value to 2
-----iteration:2-----
The index of current smallest number is: 2
3 is smaller than 4
Update lowest value to 4
-----iteration:3-----
The index of current smallest number is: 3
4 is smaller than 10
Update lowest value to 4
-----iteration:4-----
The index of current smallest number is: 4
7 is smaller than 10
Update lowest value to 5
-----iteration:5-----
The index of current smallest number is: 5

After 6 (outer loop) iterations, the array is sorted.

--

--