SORTING
Sorting refers to arranging elements in a specific order which can either be Ascending (increasing order) or Descending (decreasing order).
For instance -
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
- for i in range len(L):
- for j in range (0,len(L)-1):
- if (L[j]>L[j+1]):
- temp=L[j]
- L[j]=L[j+1]
- L[j+1]=temp
Working
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
- for i in range len(L):
- for j in range (0,i)
- if (L[i]<L[j]):
- temp=L[i]
- L[i]=L[j]
- L[j]=temp
Working
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
- for i in range len(L):
- for j in range (i+1,len(L))
- if (L[i]>L[j]):
- temp=L[i]
- L[i]=L[j]
- L[j]=temp
Working
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!!