Python Sorting Algorithms: Bubble and Merge Sort
Explore python sorting algorithms. Visualize bubble sort and merge sort natively within a browser IDE context.
How it Works
Sorting is one of the most critical operations in software engineering. While Python provides `.sort()` natively using Timsort, understanding fundamental sorting algorithms is essential for architectural knowledge.
Bubble Sort relies on brute-force O(n²) comparison swapping. Merge Sort relies on O(n log n) Divide and Conquer recursive methodologies.
Source Code
Executing a standard Bubble Sort to arrange an array in ascending order.
bubble_sort.py
Try in Editordef bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already in place
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
# Swap if the element found is greater
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped:
break
return arr
sample = [64, 34, 25, 12, 22, 11, 90]
print("Original:", sample)
print("Sorted: ", bubble_sort(sample))Terminal Output
Original: [64, 34, 25, 12, 22, 11, 90]
Sorted: [11, 12, 22, 25, 34, 64, 90]Real-world Applications
- Data pipeline cleanup and organization
- Computer science foundational learning
- Optimizing query display layers internally
Frequently Asked Questions
When should I write my own sorting function?
Rarely. You learn sorting algorithms mostly to understand algorithmic complexity. In production, always use Python’s built-in `sorted(data)` because it is highly optimized C code.