1. Bubble Sort
key Idea
Compare adjacent pairs of elements in an array and swap them if they are in the wrong order, gradually moving larger elements to the end of the array.
Time Complexity
O(n^2) in the worst and average cases
O(n) in the best case (when the input array is already sorted)
Space Complexity
- O(1)
Code
def bubble_sort(l: List[int]) -> List[int]:
n = len(l)
for i in range(n-1):
for j in range(n-i-1):
if l[j] > l[j+1]:
l[j], l[j+1] = l[j+1], l[j]
2. Selection Sort
key Idea
Find the minimum element from the unsorted portion of the array and swap it with the first unsorted element.
Time Complexity
- O(n^2) in all cases
Space Complexity
- O(1)
Code
def selection_sort(l: List[int]) -> List[int]:
n = len(l)
for i in range(n):
min_index = i
for j in range(i+1, n):
if l[min_index] > l[j]:
min_index = j
if m != i: # prevent unnecessary swap
l[i], l[m] = l[m], l[i]
3. Insertion Sort
key Idea
Take each element from the unsorted portion and insert it into its correct position within the sorted portion of the array.
Time Complexity
O(n^2) in worst case
Performs well for small or nearly sorted list.
Space Complexity
- O(1)
def insertion_sort(l: List[int]) -> List[int]:
n = len(l)
for i in range(1, n):
j = i
while l[j-1] > l[j] and j > 0:
l[j-1], l[j] = l[j], l[j-1]
j -= 1