Write a sorting algorithm for a numerical dataset in Python?

ProgrammingPythonServer Side Programming

Numerical Dataset in Python is for numerical datatypes. Sorting algorithm for integers, includes the following in Python −

  • Bubble sort
  • Shell sort
  • Selection sort

Bubble Sort in Python

Bubble Sort is comparison-based sorting. The adjacent elements are compared and swapped to make the correct sequence −

Example

def bubblesort(myList): # Swap the elements to arrange in order for iter_num in range(len(myList)-1,0,-1): for idx in range(iter_num): if myList[idx]>myList[idx+1]: temp = myList[idx] myList[idx] = myList[idx+1] myList[idx+1] = temp # Unsorted List myList = [40, 23, 7, 49, 32, 98, 76, 48, 87] print("Unsorted List = ",myList) # Calling the function bubblesort(myList) print("Sorted List = ",myList)

Output

Unsorted List =  [40, 23, 7, 49, 32, 98, 76, 48, 87]
Sorted List =  [7, 23, 32, 40, 48, 49, 76, 87, 98]

Shell Sort in Python

For Shell Sort, define a function and take a list and the length of the list as arguments. This list is sorted up to a specific number of elements, wherein the number of elements is the largest value. This is done until the number of elements has the smallest value.

Example

def shell_sort(my_list, list_len): interval = list_len // 2 while interval > 0: for i in range(interval, list_len): temp = my_list[i] j = i while j >= interval and my_list[j - interval] > temp: my_list[j] = my_list[j - interval] j -= interval my_list[j] = temp interval //= 2 my_list = [40, 23, 7, 49, 32, 98, 76, 48, 87] list_len = len(my_list) print ("The list before sorting is :") print(my_list) shell_sort(my_list, list_len) print ("
The list after performing shell sorting is :"
) print(my_list)

Output

The list before sorting is :
[40, 23, 7, 49, 32, 98, 48, 87]

The list after performing shell sorting is :
[7, 23, 32, 40, 48, 49, 87, 98]

Selection Sort in Python

In the selection sort algorithm, an array is sorted by recursively finding the minimum element from the unsorted part and inserting it at the beginning. Two subarrays are formed during the execution of Selection sort on a given array.

  • The subarray, which is already sorted

  • The subarray, which is unsorted.

Following is the code −

Example

A = ['h','o','w','a','r','e','y','o','u'] for i in range(len(A)): min_= i for j in range(i+1, len(A)): if A[min_] > A[j]: min_ = j #swap A[i], A[min_] = A[min_], A[i] # main for i in range(len(A)): print(A[i])

Output

a
e
h
o
o
r
u
w
y
raja
Updated on 12-Aug-2022 12:07:03

Advertisements