Write a sorting algorithm for a numerical dataset in Python?



Sorting refers to arranging data in a particular format. It makes the data more readable and the data searching can be optimized to a very high level. There are five different kinds of sorting algorithm.

  • Bubble sort
  • Merge sort
  • Insertion sort
  • Shell sort
  • Selection sort

Example

def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [22,43,3,21,12,31,1,2,19,10]
bubblesort(list)
print(list)

It is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

Output

[1, 2, 3, 10, 12, 19, 21, 22, 31, 43]

raja
Sri
Published on 27-May-2019 16:00:10
Advertisements