Sorting Techniques in Python – Notes

Sorting Techniques in Python

Sorting is a technique to arrange the data either in ascending or descending order. There are two types of Sorting techniques:

  • Bubble Sorting
  • Insertion Sorting

What is Sorting?

Sorting means arranging elements in a specific order – ascending (increasing order) or descending order (decreasing order) or alphabetical order.

There are multiple methods or algorithm or technique to sort a group of elements. These are – ØBubble Sort ØInsertion Sort ØSelection Sort ØQuick Sort ØHeap Sort, etc.

Types Sorting Techniques

Bubble Sort

In Bubble sort, two adjoining values are compared, and exchange them if they are not in proper order.

Bubble Sort Program

 numList = [5, 1, 4, 2, 8]
 print("List befor sorting:")
 length = len(numList)
 for i in range(length):
     for j in range(0, length-1-i):
         if numList[j] > numList[j+1]:
             numList[j], numList[j+1] = numList[j+1], numList[j]
     print("After ", i, "pass, Your List are ")

Insertion Sort

Insertion sort is based on the idea that one element from the input elements is consumed in each iteration to find its correct position i.e., the position to which it belongs in a sorted array.

It iterates the input elements by growing the sorted array at each iteration. It compares the current element with the largest value in the sorted array. If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position. This is done by shifting all the elements, which are larger than the current element, in the sorted array to one position ahead.

Insertion Sort Program

 numList = [9,7,6,15,17,5,10,11]
 print("List befor sorting:")
 length = len(numList)
 for i in range(1,length):
     key = numList[i]
     j = i - 1
     while numList[j] > key and j>=0:
         numList[j+1] = numList[j]
         j = j - 1
         numList[j+1] = key
     print("After ", i, "pass, Your List are ")

Leave a Comment

You cannot copy content of this page

Scroll to Top