How to Sort a List in Python Without using sort Function. Sorting is a fundamental concept in programming used for organizing data in a specific order. While Python provides built-in methods like 'sort()'
and 'sorted()'
for arrays, understanding how to implement sorting algorithms manually can be a great way to deepen your understanding of how sorting works. This tutorial article will guide you through the process of sorting a list in Python without using the sort
function, by implementing two classic sorting algorithms: Bubble Sort and Selection Sort.
Table of Contents
Bubble Sort in Python
Bubble sort is a simple sorting algorithm that repeatedly steps to the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Bubble Sort Implementation in Python
def bubblesort(arr):
n = len(arr)
for i in range(n):
# Track whether a swap was made during this pass
swapped = False
for j in range(0,n-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j] # swap element
swapped = True
if not swapped:
break
return arr
list = [220,231,352,865,543,343,555]
sorted_list = bubblesort(list)
print("Sorted array")
print(sorted_list)
Selection Sort in Python
Selection sort is another simple comparison-based sorting algorithm. It divides the input list into two parts: The sorted part at the beginning of the list and the unsorted part at the end of the list. The algorithm repeatedly selects the smallest (or largest) element from the unsorted sublist, swapping it with the left-most unsorted element, and moving the sublist boundaries one element to the right.
Selection Sort Implementation in Python
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range (i+1,n):
if arr[j]<arr[min_index]:
min_index = j
arr[i],arr[min_index] = arr[min_index],arr[i]
list = [220,231,352,865,543,343,555]
selection_sort(list)
print("Sorted array")
print(list)
Happy Coding & Learning
2 thoughts on “How to Sort a List in Python Without sort Function”