Selection, Insertion And Bubble Sort In Python

SORTING

 
Sorting refers to arranging elements in a specific order which can either be Ascending (increasing order) or Descending (decreasing order).
 
For instance -
 
Selection, Insertion And Bubble Sort In Python
There are multiple ways or techniques to sort a group of elements. Some known algorithms are,
  • Bubble sort
  • Insertion sort
  • Selection sort
  • Heap sort
  • Quick sort
  • Merge sort etc…
We will discuss the working and algorithm of Bubble, Selection, and Insertion sort.
 

Bubble Sort in Python

 
Bubble sort compares two adjoining values and exchanges them if they are not in the proper order.
 
In this, the heaviest element or the greatest number comes at the bottom within the initial iteration.
 
Algorithm
  1. for i in range len(L):  
  2. for j in range (0,len(L)-1):  
  3. if (L[j]>L[j+1]):  
  4. temp=L[j]  
  5. L[j]=L[j+1]  
  6. L[j+1]=temp  
Selection, Insertion And Bubble Sort In Python
 
Working
 
Selection, Insertion And Bubble Sort In Python
Selection, Insertion And Bubble Sort In Python

Insertion Sort in Python

 
Insertion sort is an algorithm that builds a sorted list, one element at a time from the unsorted list by inserting the element at its correct position in the sorted list.
 
It virtually divides the list into two sub-lists: sorted sub-list and unsorted sub-list.
 
Algorithm
  1. for i in range len(L):  
  2. for j in range (0,i)  
  3. if (L[i]<L[j]):  
  4. temp=L[i]  
  5. L[i]=L[j]  
  6. L[j]=temp  
Selection, Insertion And Bubble Sort In Python
 
Working
Selection, Insertion And Bubble Sort In Python
Selection, Insertion And Bubble Sort In Python
Selection, Insertion And Bubble Sort In Python
 

Selection Sort in Python

 
The basic idea of Selection sort is to repeatedly select the smallest key in the remaining unsorted list. It is also called and implemented in our systems as Exchange selection sort.
 
Algorithm
  1. for i in range len(L):  
  2. for j in range (i+1,len(L))  
  3. if (L[i]>L[j]):  
  4. temp=L[i]  
  5. L[i]=L[j]  
  6. L[j]=temp  
Selection, Insertion And Bubble Sort In Python
 
Working
 
Selection, Insertion And Bubble Sort In PythonSelection, Insertion And Bubble Sort In Python
 

Summary

 
In this article, we discussed a few methods of sorting. We learned selection insertion and bubble sort. I hope this will help the readers to understand how to use and implement dictionaries in Python.
 
Feedback or queries related to this article are most welcome. Thanks for reading!!


Recommended Free Ebook
Similar Articles