When learning algorithms, it’s essential to understand not only how they work but also how efficient they are in terms of time complexity. In this post, we will compare two classic sorting algorithms: Bubble Sort and Quick Sort, and we will visualize their performance using Python.
1. Bubble Sort
Bubble Sort is a simple algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until the list is sorted.
Python Implementation:
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]
return arr
2. Quick Sort
Quick Sort is a more efficient sorting algorithm that uses a divide-and-conquer approach. It picks a pivot element, partitions the array into subarrays, and recursively sorts them.
Python Implementation:
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
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)