DEV Community

Cover image for πŸš€ Sorting Algorithms Demystified: A Beginner's Guide with Python Examples
Anil Nayak
Anil Nayak

Posted on

1

πŸš€ Sorting Algorithms Demystified: A Beginner's Guide with Python Examples

Sorting is one of the most fundamental concepts in computer science. Whether you're a student, job seeker, or just a curious dev, understanding sorting algorithms is essential.

In this post, I'll break down the most popular sorting algorithms β€” Bubble Sort, Merge Sort, Quick Sort, Insertion Sort, Selection Sort, and Heap Sort β€” using simple Python examples and visuals in mind.


πŸ”„ 1. Bubble Sort – The Slow but Steady One

How it works:

Bubble Sort repeatedly compares and swaps adjacent elements if they are in the wrong order.

def bubble_sort(arr):
    for i in range(len(arr)):
        for j in range(len(arr) - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Time Complexity: O(nΒ²)
πŸ“Œ Space Complexity: O(1)
πŸ“Œ Best used for: Small datasets and educational purposes.

🧩 2. Merge Sort – Divide and Conquer FTW

How it works:
Split the list in half, recursively sort each half, and merge them back together in order.

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
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Time Complexity: O(n log n)
πŸ“Œ Space Complexity: O(n)
πŸ“Œ Best used for: Large datasets that need stable sorting.

⚑ 3. Quick Sort – The Speed Demon

How it works:
Choose a pivot, then split the list into elements less than and greater than the pivot. Recursively sort both parts.

def quick_sort(arr):
    if len(arr) <= 1:
        return arr

    pivot = arr[0]
    less = [x for x in arr[1:] if x <= pivot]
    greater = [x for x in arr[1:] if x > pivot]

    return quick_sort(less) + [pivot] + quick_sort(greater)
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Time Complexity:

Best/Average: O(n log n)

Worst: O(nΒ²) (rare case)
πŸ“Œ Space Complexity: O(log n)
πŸ“Œ Best used for: General-purpose sorting, fast in practice.

πŸ“₯ 4. Insertion Sort – Best for Nearly Sorted Data

How it works:
Build the sorted array one item at a time by inserting each element into its correct position.

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
    return arr
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Time Complexity: O(nΒ²)
πŸ“Œ Space Complexity: O(1)
πŸ“Œ Best used for: Small or nearly sorted arrays.

πŸ” 5. Selection Sort – Simple but Inefficient

How it works:
Find the minimum element in the unsorted part and move it to the beginning.

def selection_sort(arr):
    for i in range(len(arr)):
        min_idx = i
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Time Complexity: O(nΒ²)
πŸ“Œ Space Complexity: O(1)
πŸ“Œ Best used for: Simple educational use cases.

⛏️ 6. Heap Sort – Uses a Heap Data Structure

How it works:
Turn the array into a max-heap, repeatedly extract the maximum element and heapify the remaining.

def heapify(arr, n, i):
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2

    if left < n and arr[left] > arr[largest]:
        largest = left
    if right < n and arr[right] > arr[largest]:
        largest = right

    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        heapify(arr, n, largest)

def heap_sort(arr):
    n = len(arr)

    for i in range(n // 2 - 1, -1, -1):
        heapify(arr, n, i)

    for i in range(n - 1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i]
        heapify(arr, i, 0)

    return arr
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Time Complexity: O(n log n)
πŸ“Œ Space Complexity: O(1)
πŸ“Œ Best used for: Time-efficient and memory-constrained tasks.

🧠 Key Takeaways

Algorithm Time Complexity Space Complexity Best For
Bubble Sort O(nΒ²) O(1) Teaching, tiny datasets
Insertion Sort O(nΒ²) O(1) Small or nearly sorted data
Selection Sort O(nΒ²) O(1) Educational simplicity
Merge Sort O(n log n) O(n) Large datasets, stable sorting
Quick Sort O(n log n)/O(nΒ²) O(log n) Fast, general-purpose sorting
Heap Sort O(n log n) O(1) Efficient in-place sorting

πŸ§ͺ Want to Practice?

Try implementing these algorithms in:

βœ… JavaScript or C++

βœ… Visualize them using animations (React + Chart.js or Python Turtle)

βœ… Sort real-world data (JSON files, user input, logs)

πŸ™Œ Final Thoughts

Sorting may sound boring, but once you understand it β€” you've unlocked a superpower for solving real-world problems and cracking coding interviews.

If this helped you, consider giving it a ❀️ or sharing with a friend!

πŸ‘‹ Let's Connect!

πŸ“Œ GitHub

πŸ“Œ LinkedIn

πŸ“Œ Portfolio

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (0)

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one serverβ€”search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

πŸ‘‹ Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple β€œthank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay