Code ChallengesProgramming

How To Implement Bubble, Insertion And Selection Sort Algorithms In Python 3

3 Mins read

This article discusses the 3 basic python algorithms bubble, insertion and selection sort algorithms. These are the standard sorting algorithms that are commonly implemented in many languages.

Bubble, Insertion and Selection Sort Algorithms In Python 3

Bubble sort Algorithm

The bubble sort works by iterating through an array of numbers and comparing each number to the next one until it finds two numbers with a difference equal to one. It then swaps these two numbers and repeats this process until it has performed the equivalent of n-1 swaps.

It is important to note that this process is O(n^2) in terms of time complexity–the amount of time required for all permutations. In the worst case, it takes constant time, but for a typical sort, the running time is bounded by n!.

Bubble sort is based on the observation that there are many pairs of different numbers in an array where their differences are equal. For example, consider an array of numbers
for which 1 differs from 2 and 3 differs from 4. It can be seen that comparing two numbers to each other which have these differences as a common factor is not very efficient.

The algorithm can be performed as follows. The elements are numbered from 0 to “n” – 1, and we start at the first element (“n”). Whenever we find two elements that differ from each other by only one number, they swap places.

The bubble sort algorithm can be implemented in Python3 like this:

def bubble_sort(array):
    #loop through
    for iter in range(len(array)-1, 0, -1):
        for index in range(iter):
            # Compare the current to the next element in array
            if(array[index] > array[index+1]):
                #Swap the two
                temp = array[index]
                array[index] = array[index+1]
                array[index+1] = temp
    return array

Insertion sort algorithm

The insertion sort algorithm is the simplest sorting algorithm of them all. It sorts an array by inserting (or “inserting into”) the elements so that each element is sorted in ascending order. It does this by repeatedly splitting the array in half and comparing the two halves; when they are equal, it moves one of them over towards its right neighbour – which will stop when there is no more room to move.

The algorithm works on a binary search tree, where nodes have two properties: left and right. The left property is used to keep track of the positions of the left half of the nodes and the right property is used for tracking the position of the right half.

The tree will have as many splits in it, because when one side runs out of room to move, it will have been sorted. So, in each step, we check whether there are still elements to be moved or not. If there are no more elements to transfer, we return from this pass; otherwise we keep going.

Let’s have a look at how to perform an insertion sort:

def insertion_sort(list):
    for index in range(1, len(list)):
        key = list[index]
        j = index - 1
        while j >= 0 and key < list[j]:
            list[j + 1] = list[j]
            j -= 1
        list[j + 1] = key
    return list

Selection sort Algorithm

As you can see, the selection sort algorithm is a simple one and very easy to understand. The only instances where this algorithm would be preferable to bubble sort or insertion sort are when the list is already in order and there are few elements in it (as these sort algorithms’ times increase exponentially with the size of their inputs).

The first step is to create a list that contains all the numbers from 1 – N. If you already have a list then you can skip this part.

Then you have to ensure that the number that is being sorted is 1st.

You can keep track of the numbers that are already sorted and make sure that the first number is always at the top. So, in Python this would look like this.

def selection_sort(list):
    n = len(list)
    for i in range(n - 1):
        min_value_index = i

        for j in range(i + 1, n):
            if list[j] < list[min_value_index]:
                min_value_index = j

        if min_value_index != i:
            temp = list[i]
            list[i] = list[min_value_index]
            list[min_value_index] = temp
    return list


Bubble sort, selection sort and insertion sort algorithms are simple algorithms that can be implemented in any programming language. Both of them have their uses, some more than others, but whatever the situation is, they are all relatively very efficient.

You might be interested in Why code reviews are important

Don’t miss amazing tips!

Related posts
How ToProgrammingSoftwareTechnology

How to configure Apache Airflow on MacOS locally

4 Mins read
Table of contents0.1 Creating the project folder and the virtual environment0.2 Installing0.3 Running airflow0.4 Starting the webflow server0.5 Starting the scheduler0.6 Running…
Code ChallengesHow ToProgrammingSoftware

How To Implement Merge Sort and Quick Sort Algorithms In Python 3

3 Mins read
Table of contents0.1 Merge Sort0.2 Quick Sort0.3 Conclusion1 Don’t miss amazing tips! Let’s have a look at how to how to implement…
How ToProgrammingSoftware

How to link flutter with firebase email password authentication

11 Mins read
Table of contents0.1 firebase email password authentication output flow0.2 Creating our email password authentication on flutter0.3 Step 10.4 Setting up firebase and…

Leave a Reply

Your email address will not be published. Required fields are marked *

− 1 = 1


Why are Code reviews important?