Algorithms and Data Structures in Python: Selection Sort


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:

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