Bubble Sort, Selection Sort & Insertion Sort

Ye teeno sorting algorithms simple aur beginners ke liye useful hain, jo chhoti datasets ke liye acha kaam karte hain. Inka samajhna kisi bhi programming ya data structure course ke liye zaruri hai.

1. Bubble Sort

Bubble Sort repeatedly adjacent elements ko compare karta hai aur swap karta hai agar order galat ho. Har pass ke baad largest element apni correct jagah par pahunch jata hai.

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break  # Stop if array is already sorted

2. Selection Sort

Selection Sort har pass me unsorted part me minimum element dhundh kar, usse current position par swap karta hai.

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

Insertion Sort left se sorted subarray banata hai aur har step pe new element ko uske sahi position par insert karta hai.

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key

Algorithm Comparison

Algorithm Time Complexity (Best) Time Complexity (Average/Worst) Space Complexity Stability Use Case
Bubble Sort O(n) O(n²) O(1) Stable Simple and small datasets
Selection Sort O(n²) O(n²) O(1) Unstable Small datasets, memory constrained
Insertion Sort O(n) O(n²) O(1) Stable Nearly sorted datasets