1. Home
  2. Explore
  3. Computer Science
  4. Sorting Algorithms

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Sorting Algorithms

📚 Sorting Algorithms & Complexity

This section delves into various sorting algorithms, analyzing their efficiency and comparing their performance. We'll start with less efficient methods and progress to more optimized approaches, ultimately arriving at the most efficient sorting algorithms.

🔍 The Need for Sorting

Before exploring sorting algorithms, it's crucial to understand why sorting is so important. When searching for elements within a list, two primary algorithms exist: linear search and binary search.

  • Linear Search:

    • Works on both sorted and unsorted lists.

    • Its worst-case time complexity is Θ(n)\Theta(n)Θ(n), meaning it has to check, on average, every element in the list.

  • Binary Search:

    • Requires a sorted list to function correctly.

    • Offers a significantly faster worst-case time complexity of Θ(log⁡n)\Theta(\log n)Θ(logn).

The advantage of binary search is clear: Θ(log⁡n)\Theta(\log n)Θ(logn) is much faster than Θ(n)\Theta(n)Θ(n) for large lists. However, the requirement for a sorted list introduces a dilemma: if a list is unsorted, it must first be sorted.

🤔 When to Use Binary Search?

The decision to use binary search depends on the frequency of searches.

  • Single Search: If you only need to search for an element once, sorting the list first (which takes at least Θ(n)\Theta(n)Θ(n) time) and then performing a binary search (Θ(log⁡n)\Theta(\log n)Θ(logn)) will likely be slower than just performing a linear search (Θ(n)\Theta(n)Θ(n)). This is because the sorting cost dominates.

    • Time(Sort) + Time(Binary Search) < Time(Linear Search)

    • Time(Sort) + Θ(log n) < Θ(n)

    • Time(Sort) < Θ(n) - Θ(log n)

    • This inequality implies that sorting could be done in less than Θ(n)\Theta(n)Θ(n) time, which is impossible as every element must be examined at least once to confirm sorted order.

  • Multiple Searches: Binary search becomes highly advantageous when performing many searches on the same dataset. The cost of sorting is incurred only once and then amortized over k searches. As k (the number of searches) increases, the per-search cost of sorting approaches zero, making binary search on a pre-sorted list far more efficient than k linear searches.


🎲 Bogo Sort: The "Bad" Algorithm

Bogo Sort (also known as random sort or monkey sort) is an intentionally inefficient sorting algorithm that illustrates how not to approach sorting.

💡 How it Works

The core idea is to use randomness:

  1. Shuffle: Randomly reorder the elements in the list.

  2. Check: Determine if the list is sorted.

  3. Repeat: If not sorted, repeat steps 1 and 2.

import random

def is_sorted(L):
    for i in range(len(L) - 1):
        if L[i] > L[i+1]:
            return False
    return True

def bogo_sort(L):
    shuffles = 0
    while not is_sorted(L):
        random.shuffle(L) # Randomly shuffles the list
        shuffles += 1
    return shuffles

⏱️ Complexity Analysis

  • Best Case: Θ(n)\Theta(n)Θ(n)

    • If the input list is already sorted, is_sorted will iterate through all n elements once to confirm. No shuffles are needed.

  • Worst Case: Unbounded (∞\infty∞)

    • In the worst theoretical scenario, the list might never be randomly shuffled into a sorted order. While highly improbable for practical list sizes, it's theoretically possible.

  • Average Case: Extremely poor (factorially related to n).

Bogo Sort is a prime example of an algorithm that makes "forward progress" but is fundamentally impractical due to its reliance on chance.


🫧 Bubble Sort: The "Popular" Bad Algorithm

Bubble Sort is one of the simplest sorting algorithms to understand, but it's often used as an example of an inefficient algorithm.

💡 How it Works

Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

  1. Consecutive Comparisons: Start at the beginning of the list and compare the first two elements.

  2. Swap if Needed: If the first element is greater than the second, swap them.

  3. Move to Next Pair: Move to the next pair of elements (second and third) and repeat the comparison and swap.

  4. "Bubble Up": After one full pass, the largest element will "bubble up" to its correct position at the end of the list.

  5. Repeat Passes: Repeat the entire process for the remaining unsorted portion of the list. If no swaps occur during a pass, the list is sorted.

Example Walkthrough: Start: [5, 8, 4, 1, 11, 6, 2, 0]

Pass 1:

  • [5, 8, 4, 1, 11, 6, 2, 0] -> [5, 8, 4, 1, 11, 6, 2, 0] (5 < 8, no swap)

  • [5, 8, 4, 1, 11, 6, 2, 0] -> [5, 4, 8, 1, 11, 6, 2, 0] (8 > 4, swap)

  • [5, 4, 8, 1, 11, 6, 2, 0] -> [5, 4, 1, 8, 11, 6, 2, 0] (8 > 1, swap)

  • [5, 4, 1, 8, 11, 6, 2, 0] -> [5, 4, 1, 8, 6, 11, 2, 0] (11 > 6, swap)

  • ...and so on, until 11 is at the end. After Pass 1: [5, 4, 1, 6, 2, 0, 8, 11] (11 is now in its correct place)

Pass 2:

  • Repeat comparisons, but now exclude the last element (11) as it's sorted.

  • After Pass 2: [4, 1, 2, 0, 5, 6, 8, 11] (8 is now in its correct place)

This process continues until a full pass occurs with no swaps, indicating the list is sorted.

💻 Code Structure

def bubble_sort(L):
    swapped = True
    while swapped:
        swapped = False # Assume no swaps for this pass
        for j in range(1, len(L)): # Iterate through elements
            if L[j-1] > L[j]: # Compare adjacent elements
                L[j-1], L[j] = L[j], L[j-1] # Perform swap
                swapped = True # A swap occurred, so another pass is needed
    return L

⏱️ Complexity Analysis

  • Inner For Loop: The for loop iterates n-1 times, performing comparisons and potential swaps. This is Θ(n)\Theta(n)Θ(n).

  • Outer While Loop: In the worst case, the list is sorted in reverse order. Each pass of the while loop only places one element in its correct final position. Thus, it will require n passes.

    • Example: [3, 2, 1]

      • Pass 1: [2, 1, 3] (3 is in place)

      • Pass 2: [1, 2, 3] (2 is in place)

      • Pass 3: [1, 2, 3] (1 is in place, no swaps this pass)

  • Worst Case Time Complexity: Θ(n2)\Theta(n^2)Θ(n2)

    • The while loop runs n times, and inside it, the for loop runs n times. n×n=n2n \times n = n^2n×n=n2.

Bubble Sort's inefficiency stems from its repetitive comparisons of elements that are already in their correct relative positions.


🎯 Selection Sort: A Smarter Approach

Selection Sort is an improvement over Bubble Sort because it makes fewer swaps, but its asymptotic complexity remains the same.

💡 How it Works

Selection Sort works by repeatedly finding the minimum element from the unsorted part of the list and putting it at the beginning of the sorted part.

  1. Find Minimum: In the first pass, iterate through the entire list to find the smallest element.

  2. Place at Beginning: Swap this smallest element with the element at the first position (index 0). Now, the first element is sorted.

  3. Repeat for Remaining: In the second pass, iterate through the remaining unsorted portion of the list (from index 1 to the end) to find the next smallest element.

  4. Place at Next Position: Swap this smallest element with the element at the second position (index 1). Now, the first two elements are sorted.

  5. Continue: Repeat this process, moving the "boundary" of the sorted portion one element at a time until the entire list is sorted.

Example Walkthrough: Start: [5, 8, 4, 1, 11, 6, 2, 0]

Pass 1 (Find min for index 0):

  • Current min: 5 (at index 0)

  • Compare 5 with 8, 4, 1, 11, 6, 2, 0.

  • Smallest found is 0 (at index 7).

  • Swap 5 and 0. After Pass 1: [0, 8, 4, 1, 11, 6, 2, 5] (0 is now in its correct place)

Pass 2 (Find min for index 1):

  • Current min: 8 (at index 1)

  • Compare 8 with 4, 1, 11, 6, 2, 5.

  • Smallest found is 1 (at index 3).

  • Swap 8 and 1. After Pass 2: [0, 1, 4, 8, 11, 6, 2, 5] (1 is now in its correct place)

This continues until all elements are in their correct positions.

💻 Code Structure

def selection_sort(L):
    for i in range(len(L)): # Outer loop: iterate through each position to fill
        min_idx = i # Assume current element is the minimum
        for j in range(i + 1, len(L)): # Inner loop: find smallest in unsorted part
            if L[j] < L[min_idx]:
                min_idx = j # Update index of minimum element
        # Swap the found minimum element with the element at current position i
        L[i], L[min_idx] = L[min_idx], L[i]
    return L

⏱️ Complexity Analysis

Selection Sort has two nested loops:

  • Outer Loop: Iterates n times (from i = 0 to n-1). This is Θ(n)\Theta(n)Θ(n).

  • Inner Loop:

    • First pass (i=0): Iterates n-1 times.

    • Second pass (i=1): Iterates n-2 times.

    • ...

    • Last pass (i=n-2): Iterates 1 time.

    • The number of comparisons is (n−1)+(n−2)+⋯+1=(n−1)n2(n-1) + (n-2) + \dots + 1 = \frac{(n-1)n}{2}(n−1)+(n−2)+⋯+1=2(n−1)n​.

  • Worst Case Time Complexity: Θ(n2)\Theta(n^2)Θ(n2)

    • The sum of comparisons is approximately n22\frac{n^2}{2}2n2​, which is still Θ(n2)\Theta(n^2)Θ(n2).

    • Even with fewer swaps than Bubble Sort, the number of comparisons remains quadratically dependent on n.

While Selection Sort performs fewer swaps, its fundamental approach of iterating through a shrinking unsorted sublist for each position results in the same Θ(n2)\Theta(n^2)Θ(n2) time complexity as Bubble Sort.


🌳 Merge Sort: Divide and Conquer

Merge Sort is a highly efficient, comparison-based sorting algorithm that utilizes the divide and conquer paradigm. It's designed to achieve a better time complexity than the O(n2)O(n^2)O(n2) algorithms.

💡 How it Works: Divide and Conquer

Merge Sort breaks down a list into several sub-lists until each sub-list consists of a single element (which is by definition sorted). Then, it repeatedly merges these sub-lists to produce new sorted sub-lists until there is only one sorted list remaining.

  1. Divide: Recursively split the unsorted list into two halves until each sub-list contains only one element. A list with one element is considered sorted.

  2. Conquer (Sort): Sort the sub-lists (base case: a single element is already sorted).

  3. Combine (Merge): Repeatedly merge sub-lists to produce new sorted sub-lists. This is the critical step where the actual sorting work happens efficiently.

The Merge Step Explained

The efficiency of Merge Sort comes from its intelligent merge operation. If you have two already sorted sub-lists, merging them into a single sorted list is very fast.

Example: Merging [0, 2, 5, 9] and [1, 4, 6, 8]

  • Compare the first elements of each list: 0 vs 1. 0 is smaller, add 0 to the result.

    • Result: [0]

    • Lists: [2, 5, 9] and [1, 4, 6, 8]

  • Compare 2 vs 1. 1 is smaller, add 1 to the result.

    • Result: [0, 1]

    • Lists: [2, 5, 9] and [4, 6, 8]

  • Compare 2 vs 4. 2 is smaller, add 2 to the result.

    • Result: [0, 1, 2]

    • Lists: [5, 9] and [4, 6, 8]

  • Compare 5 vs 4. 4 is smaller, add 4 to the result.

    • Result: [0, 1, 2, 4]

    • Lists: [5, 9] and [6, 8]

  • ...and so on.

  • When one list becomes empty, simply append the remaining elements of the other list to the result (as they are already sorted).

This merge process touches each element only once, making it a Θ(n)\Theta(n)Θ(n) operation for lists of total length n.

💻 Code Structure

Merge Sort consists of two main functions: merge_sort (the recursive divide function) and merge (the combining function).

merge Function

def merge(left, right):
    result = []
    i, j = 0, 0 # Pointers for left and right lists

    # Compare elements from both lists and add the smaller one to result
    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

    # Add remaining elements from left list (if any)
    while i < len(left):
        result.append(left[i])
        i += 1

    # Add remaining elements from right list (if any)
    while j < len(right):
        result.append(right[j])
        j += 1
    return result

merge_sort Function

def merge_sort(L):
    # Base case: A list with 0 or 1 element is already sorted
    if len(L) < 2:
        return L

    # Divide: Find the midpoint and split the list into two halves
    mid = len(L) // 2
    left = L[:mid]
    right = L[mid:]

    # Conquer: Recursively sort the left and right halves
    sorted_left = merge_sort(left)
    sorted_right = merge_sort(right)

    # Combine: Merge the sorted halves
    return merge(sorted_left, sorted_right)

⏱️ Complexity Analysis

The complexity of Merge Sort can be analyzed by considering the divide and merge steps.

  1. Number of Levels (Divide Phase):

    • The list is repeatedly divided in half until single-element lists are formed.

    • This process is similar to binary search, where n elements are divided by 2 repeatedly until 1 element remains.

    • The number of times this division occurs is log⁡2n\log_2 nlog2​n. So there are Θ(log⁡n)\Theta(\log n)Θ(logn) levels of recursion.

  2. Work per Level (Merge Phase):

    • At each level of the recursion (when merging back up), the merge function processes all n elements across all sub-lists at that level.

    • For example, if you have n/2 lists of size 2, merging them takes n/2 * (2 comparisons) which is n comparisons.

    • Therefore, the merge step at each level takes Θ(n)\Theta(n)Θ(n) time.

  3. Total Complexity:

    • Total time = (Number of levels) ×\times× (Work per level)

    • Total time = Θ(log⁡n)×Θ(n)=Θ(nlog⁡n)\Theta(\log n) \times \Theta(n) = \Theta(n \log n)Θ(logn)×Θ(n)=Θ(nlogn)

  • Worst Case Time Complexity: Θ(nlog⁡n)\Theta(n \log n)Θ(nlogn)

  • Best Case Time Complexity: Θ(nlog⁡n)\Theta(n \log n)Θ(nlogn) (Merge Sort always performs the same number of comparisons and merges, regardless of the initial order)

  • Average Case Time Complexity: Θ(nlog⁡n)\Theta(n \log n)Θ(nlogn)

Merge Sort is one of the most efficient sorting algorithms, achieving the theoretical lower bound for comparison-based sorting algorithms, which is Θ(nlog⁡n)\Theta(n \log n)Θ(nlogn). This makes it significantly faster than Θ(n2)\Theta(n^2)Θ(n2) algorithms for large datasets.

📈 Guiding Program Design with Complexity Analysis

Understanding complexity analysis is crucial for guiding the design of efficient programs.

  • Identify Bottlenecks: If an initial design involves nested loops (e.g., for loops inside for loops), this immediately suggests a Θ(n2)\Theta(n^2)Θ(n2) or higher complexity.

  • Rethink Design: Knowing the complexity allows developers to decide if a design needs to be fundamentally rethought. A Θ(n2)\Theta(n^2)Θ(n2) algorithm might be acceptable for small n, but for large datasets, it will be prohibitively slow.

  • Choose Optimal Algorithms: Complexity analysis helps in choosing algorithms that scale well with increasing data size, such as opting for Merge Sort (Θ(nlog⁡n)\Theta(n \log n)Θ(nlogn)) over Bubble Sort (Θ(n2)\Theta(n^2)Θ(n2)) for sorting large lists.

By analyzing the complexity early in the design phase, developers can avoid writing inefficient code and instead focus on approaches that offer better performance characteristics.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent