Sorting Algorithms in Python
Sorting Algorithms in Python is a core Python concept covering sorting Algorithms in Python: --8<: "core-logic/sorting-algorithms.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Sorting Algorithms
Sorting is the process of arranging items in a specific order (usually ascending or descending).
Common Sorting Strategies
- Bubble Sort: Repeatedly swap adjacent elements if they are in the wrong order. Small values "bubble" to the top.
- Selection Sort: Find the smallest element and move it to the beginning. Repeat for the rest.
- Insertion Sort: Build the sorted list one item at a time by inserting each new item into its correct position.
- Merge Sort: Divide the list into halves, sort each half, and then merge them back together. (Fast and reliable).
- Quick Sort: Pick a "pivot" element and partition the list around it. (Very fast in practice).
In computer science, we measure how "expensive" an algorithm is using Big O Notation. Simple sorts (Bubble, Selection) are usually $O(n^2)$, while advanced sorts (Merge, Quick) are $O(n \log n)$.
1. Bubble Sort
def bubble_sort(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] # Swap
return arr
print(bubble_sort([64, 34, 25, 12, 22]))
2. Quick Sort (Recursive)
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
print(quick_sort([64, 34, 25, 12, 22]))
Python's Built-in Sort: Timsort
In real-world Python development, we rarely write our own sorting algorithms. Python uses a highly optimized algorithm called Timsort (a hybrid of Merge Sort and Insertion Sort).
# Modifies the original list
mylist = [5, 2, 9, 1]
mylist.sort()
# Returns a new sorted list
newlist = sorted([5, 2, 9, 1])
Python's sort() and sorted() are written in C and are extremely fast. Always use them unless you are explicitly asked to implement a specific algorithm for an exam or interview.