Algorithms and Data Structures in Python: Selection Sort

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.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Headless & WebSecurity Capabilities on Browsers

Background on Identifying problems and how the Software helped to make the World a Better place.

hasura-cli “Killed:9” Issue

Team: Welcoming Ekaterina Skorobogatova, former Growth Manager at WhatsApp!

How can quality metrics improve SDLC?

Free static IP for BTC/Lightning Node

Setting up SQL Cloud (MS SQL Server) on GCP

How to profile & debug iOS and Android React Native projects

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yue

Yue

More from Medium

The helicopter view of Python (for intermediate) part 1

Leetcode 1886. Determine Whether Matrix Can Be Obtained By Rotation

image.png

Why you should learn SQL…? & SQLite 3 in python.

Pattern Programming in python