DEV Community

Nitinn S Kulkarni
Nitinn S Kulkarni

Posted on

Part 6: Sorting Algorithms in Python โ€“ Concepts, Code, and Complexity

๐Ÿš€ Introduction

Sorting is a fundamental operation in programming โ€” and mastering sorting algorithms helps you understand time complexity, algorithm design, and even how Pythonโ€™s built-in tools work under the hood.

In this post, weโ€™ll explore:

โœ… Basic and advanced sorting algorithms

โœ… Python implementations with step-by-step logic

โœ… When to use each sorting method

โœ… Built-in sorting (sorted(), list.sort()) and how it's optimized

โœ… Time & space complexity comparison


๐Ÿ“š 1๏ธโƒฃ Why Sorting Matters

Sorting is used everywhere:

1. Organizing data before searching (e.g., binary search)

2. Making duplicate detection easier

3. Efficient comparisons, merging, and filtering

4. Preprocessing before solving harder problems (e.g., greedy, DP)
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก 2๏ธโƒฃ Built-in Sorting in Python

๐Ÿ”น sorted() โ€“ returns a new sorted list


nums = [5, 2, 9, 1]
sorted_nums = sorted(nums)

Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น list.sort() โ€“ sorts in place


nums.sort()

Enter fullscreen mode Exit fullscreen mode

โœ… Both use Timsort, a hybrid of merge and insertion sort

๐Ÿ•’ Time complexity: O(n log n) (worst-case)


๐Ÿงฎ 3๏ธโƒฃ Selection Sort โ€“ Simple but Inefficient


def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_i = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_i]:
                min_i = j
        arr[i], arr[min_i] = arr[min_i], arr[i]
    return arr

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Time: O(nยฒ)

โœ… Easy to understand

โŒ Not suitable for large data


๐Ÿ” 4๏ธโƒฃ Bubble Sort โ€“ Compare and Swap


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]
    return arr

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Time: O(nยฒ)

โœ… Good for teaching purposes

โŒ Inefficient for real-world use


๐ŸงŠ 5๏ธโƒฃ Insertion Sort โ€“ Builds Sorted Portion


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
    return arr

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Time: O(nยฒ), but efficient for small or nearly sorted arrays

โœ… Used in Timsort for small runs


๐Ÿงฌ 6๏ธโƒฃ Merge Sort โ€“ Divide and Conquer


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 = []
    l = r = 0

    while l < len(left) and r < len(right):
        if left[l] < right[r]:
            result.append(left[l])
            l += 1
        else:
            result.append(right[r])
            r += 1
    result.extend(left[l:])
    result.extend(right[r:])
    return result

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Time: O(n log n)

๐Ÿง  Space: O(n)

โœ… Stable, consistent

โœ… Great for linked lists or external sorting


โšก 7๏ธโƒฃ Quick Sort โ€“ Efficient and Elegant


def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[0]
    less = [x for x in arr[1:] if x <= pivot]
    more = [x for x in arr[1:] if x > pivot]
    return quick_sort(less) + [pivot] + quick_sort(more)

Enter fullscreen mode Exit fullscreen mode

๐Ÿ“ฆ Time:

Average: O(n log n)

Worst: O(nยฒ) (rare, with bad pivots)
Enter fullscreen mode Exit fullscreen mode

โœ… Fast and in-place (with extra work)

โŒ Unstable


๐Ÿ“Š 8๏ธโƒฃ Comparison Table

Algorithm Time Complexity Space Stable? Use When
Selection Sort O(nยฒ) O(1) โŒ
Bubble Sort O(nยฒ) O(1) โœ…
Insertion Sort O(nยฒ), Best: O(n) O(1) โœ…
Merge Sort O(n log n) O(n) โœ…
Quick Sort O(n log n), Worst O(nยฒ) O(log n) โŒ
Timsort (Python) O(n log n) O(n) โœ…

๐Ÿง  Real-World Tips

โœ… For large unsorted datasets โ†’ Timsort (default)

โœ… For small arrays or known order โ†’ Insertion Sort

โœ… For linked lists โ†’ Merge Sort

โœ… For interview practice โ†’ Quick Sort is a favorite


๐Ÿงช Practice Problems

Problem Technique
Sort Colors (Dutch Flag) Custom in-place sort
Merge Intervals Sorting + merging
Top K Frequent Elements Sorting by frequency
Largest Number Custom sort with key
Kth Largest Element Quickselect

โœ… Summary

โœ”๏ธ Sorting algorithms vary in efficiency, stability, and use cases
โœ”๏ธ Learn basic ones for intuition, master advanced ones for performance
โœ”๏ธ Python uses Timsort, a hybrid of merge and insertion sort
โœ”๏ธ In interviews, know when and why to choose a specific algorithm
๐Ÿ”œ Coming Up Next:

๐Ÿ‘‰ Part 7: Searching Algorithms โ€“ Binary Search and Its Powerful Variants

Weโ€™ll cover:

1. Linear vs Binary Search

  1. Binary search templates

  2. Search in rotated array

  3. Lower/upper bounds

  4. Real-world applications

Enter fullscreen mode Exit fullscreen mode




๐Ÿ’ฌ Have a sorting trick or a favorite sorting bug story? Drop it in the comments and letโ€™s learn together! ๐Ÿง ๐Ÿ“ˆ

Top comments (0)