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.
def 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))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.
More Examples
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.