Python Sort Algorithms 📶
Sorting
Sorting is the process of arranging data in a specific order. This order is most often numerical or lexicographical.
✨ Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
python
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" %arr[i])🎮 Interactive Bubble Sort Demo
Speed:
ℹ️ Ready
Comparing/Active
Sorted
⚡ Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
python
import sys
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
print("Sorted array")
for i in range(len(A)):
print("%d" %A[i])🎮 Interactive Selection Sort Demo
Speed:
ℹ️ Ready
Comparing/Active
Sorted
✨ Pro Tip
Python's built-in sort() method uses Timsort, which is a hybrid sorting algorithm, derived from merge sort and insertion sort.