1. BUBBLE SORT
Repeatedly compare adjacent elements and swap if they are in wrong order. Biggest element “bubbles” to the end each pass.
Steps
- Start from index 0
- Compare arr[j] and arr[j+1]
- Swap if left > right
- Continue till end
- Repeat for n passes
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
2. SELECTION SORT
Find the smallest element and place it at the correct position.
Steps
- Assume first element is minimum
- Check rest of array
- Find actual minimum
- Swap with first
- Move to next position
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
3. INSERTION SORT
Build sorted array one element at a time, like arranging cards.
Steps
- Start from index 1
- Take current element
- Compare with left side
- Shift bigger elements right
- Insert at correct position
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
4. MERGE SORT
Divide array into halves → sort them → merge back
StepS
- Divide array into 2 halves
- Recursively sort both halves
- Merge sorted halves
- Repeat until fully sorted
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
Top comments (0)