softwarerror

Sorting Algorithms

🫧 Bubble Sort

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process repeats until the list is sorted.

def bubble_sort(arr):
    n = len(arr)  # <-- Get length of passed array
    for i in range(n):  # <-- Loop through array
        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

🧠 Time Complexity

Bubble Sort is inefficient on large datasets, but useful for teaching algorithm fundamentals.

📊 Visual Comparison:

Bubble Sort Time Complexity Graph

🧩 Insertion Sort

Insertion Sort builds the final sorted array one item at a time. It takes each element and places it in its correct position among the already-sorted elements. This makes it efficient for small datasets or arrays that are mostly sorted.

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        # Move elements of arr[0..i-1], that are greater than key,
        # to one position ahead of their current position
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr

🧠 Time Complexity

Insertion Sort is intuitive and stable. It’s commonly used for teaching purposes or when sorting small batches of data quickly.

📊 Visual Comparison:

Insertion Sort Time Complexity Graph