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

Study methods

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

Sorting Algorithms Overview

Sorting Algorithms Study Notes

Overview of Sorting

Sorting is a fundamental operation in computer science. It arranges elements in a sequence (typically an array) into a specified order — ascending (smallest to largest) or descending (largest to smallest). This guide covers five popular sorting algorithms, their visual mechanics, implementations, and performance characteristics.


Basic Sorting Algorithm (Naive Comparison Sort)

This is the simplest approach: use a nested loop to compare every pair of elements and swap whenever an element at a later index is smaller than the element at an earlier index.

How It Works

  • Use two index variables: i starts at 0, j starts at i+1.

  • For each i, iterate j from i+1 to the end of the array.

  • If array[j] < array[i], swap the two values using a temporary variable.

  • After the inner loop completes, the smallest element among the remaining ones moves to position i.

  • Continue until i reaches the second‑last element.

Visual Walkthrough (4-element example)

Array: [2, 3, 1, 5]

  • i=0, j=1: 3 < 2? No → no swap.

  • i=0, j=2: 1 < 2? Yes → swap 2 and 1 → [1, 3, 2, 5].

  • i=0, j=3: 5 < 1? No.

  • i=1, j=2: 2 < 3? Yes → swap 3 and 2 → [1, 2, 3, 5].

  • i=1, j=3: 5 < 2? No.

  • i=2, j=3: 5 < 3? No.

Final sorted array: [1, 2, 3, 5].

C++ Code Sketch

for (int i = 0; i < n; i++) {
    for (int j = i+1; j < n; j++) {
        if (array[j] < array[i]) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
}

Time Complexity

  • Worst‑case and average‑case: O(n2)O(n^2)O(n2) – due to nested loops.

  • Best‑case: O(n2)O(n^2)O(n2) – always compares all pairs.

This algorithm is easy to understand but very inefficient for large datasets.


Selection Sort

Selection sort improves the naive method by reducing the number of swaps. It finds the smallest element in the unsorted portion and places it at the current position in one swap.

How It Works

  • Maintain a location index for the smallest element found so far.

  • For each position i from 0 to n-2:

    • Call a helper function locationOfSmallest(array, i, n-1) to find the index of the minimum element in the subarray from i to the end.

    • Swap array[i] with array[minIndex] using a swap function.

Key Functions

  • swap(array, x, y): exchanges array[x] and array[y].

  • locationOfSmallest(array, start, end): returns the index of the smallest element in the range [start, end]. It iterates from start to end and tracks the smallest value.

Visual Example

Initial array: [5, 4, 3, 7, 9]

  • i=0: Find smallest in [0..4] → value 3 at index 2. Swap 5 and 3 → [3, 4, 5, 7, 9].

  • i=1: Find smallest in [1..4] → value 4 at index 1 (already in place). No swap.

  • i=2: Find smallest in [2..4] → value 5 at index 2. No swap.

  • Continue; array becomes sorted after each pass places the smallest remaining element correctly.

C++ Code Sketch

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        int j = locationOfSmallest(arr, i, n-1);
        swap(arr, i, j);
    }
}

Time Complexity

  • All cases: O(n2)O(n^2)O(n2) comparisons; but only O(n)O(n)O(n) swaps.

  • Simpler than bubble sort in terms of swaps but still quadratic.


Bubble Sort

Bubble sort works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This causes larger elements to "bubble" to the end.

How It Works

  • Start from the bottom (last element) and compare adjacent pairs moving upward.

  • For each pass from n-1 down to 1:

    • Compare array[i] and array[i-1]. If array[i] < array[i-1], swap them.

  • After one full pass, the smallest element moves to the beginning.

  • Repeat for n-1 passes; after each pass, the next smallest element is placed correctly.

Visual Walkthrough (5 elements)

Initial: [3, 5, 1, 4, 3]

  • Pass 1 (bubble upward):

    • Compare 3 and 4 → 4 heavier, stay.

    • Compare 1 and 5 → swap → [3,1,5,4,3]

    • Compare 5 and 3 → etc. After full pass, smallest 1 at front.

  • Pass 2: Next smallest 3 moves to second position.

  • Continue until sorted.

Floating‑Up Analogy

  • Bubble (lighter) rises to the top; heavier elements sink to the bottom.

  • Adjacent comparisons simulate this buoyancy effect.

C++ Code Sketch

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        // Bubble the smallest element to position i
        for (int j = n-1; j > i; j--) {
            if (arr[j] < arr[j-1]) {
                swap(arr, j, j-1);
            }
        }
    }
}

Time Complexity

  • Worst‑case and average‑case: O(n2)O(n^2)O(n2).

  • Best‑case (already sorted): O(n)O(n)O(n) with early termination check (not implemented above).


Insertion Sort

Insertion sort builds the final sorted array one element at a time. It assumes that a prefix of the array is already sorted, and inserts the next element into its correct position.

How It Works

  • Start with i = 1 (the second element). Assume the first element (index 0) is already sorted.

  • For each i:

    • Store the current element as key = array[i].

    • Set j = i-1 (the last index of the sorted part).

    • Shift elements in the sorted part to the right until the correct insertion point is found: while (j >= 0 && array[j] > key) → array[j+1] = array[j]; j--.

    • Place the key at array[j+1].

Visual Example: [3, 7, 9, 4]

  • i=1: key = 7. Sorted part [3]. 3 < 7 → no shift. Insert 7 after 3: [3,7,9,4].

  • i=2: key = 9. Sorted part [3,7]. 7 < 9, 3 < 9 → no shift. Insert 9: [3,7,9,4].

  • i=3: key = 4. Sorted part [3,7,9]. Compare 9 > 4 → shift 9 right → [3,7,9,9]. Compare 7 > 4 → shift 7 right → [3,7,7,9]. Compare 3 > 4? No → stop. Insert key at index 1: [3,4,7,9].

C++ Code Sketch

void insertionSort(int arr[], int n) {
    for (int i = 1; i < n; i++) {
        int key = arr[i];
        int j = i-1;
        while (j >= 0 && arr[j] > key) {
            arr[j+1] = arr[j];
            j--;
        }
        arr[j+1] = key;
    }
}

Time Complexity

  • Worst‑case (reverse sorted): O(n2)O(n^2)O(n2) – every element shifts through the entire sorted part.

  • Best‑case (already sorted): O(n)O(n)O(n) – no shifts needed.

  • Average‑case: O(n2)O(n^2)O(n2).

  • Very efficient for small or nearly sorted arrays.


Merge Sort

Merge sort is a divide‑and‑conquer algorithm that splits the array into halves, recursively sorts each half, and then merges the two sorted halves into one.

How It Works

  • Divide: Recursively split the array into two halves until each sub‑array contains one element (a single element is trivially sorted).

  • Conquer: Merge two sorted sub‑arrays into a single sorted array using two pointers and a temporary buffer.

Visual Process (10 elements example)

Array: [2, 7, 4, 5, 11, 15, 3, 8, 19, 21] (split into two sorted halves assumed)

  • First half sorted: [2,7,4,5,11]? Actually the example assumes first half [2,7,4,5,11] and second half [15,3,8,19,21] – but they are not sorted; the algorithm ensures they become sorted recursively.

  • After recursion, we have two sorted sub‑arrays: e.g., left = [2,4,5,7,11], right = [3,8,15,19,21].

  • Merge:

    • Compare 2 and 3 → 2 placed, increment left index.

    • Compare 4 and 3 → 3 placed, increment right index.

    • Continue: 4 vs 8 → 4, etc.

    • When one sub‑array is exhausted, append the remaining elements of the other.

Recursive Structure

  • Base case: if start >= end, return (single element or empty).

  • Find mid: mid = (start + end) / 2.

  • Recursively sort left half (start to mid) and right half (mid+1 to end).

  • Merge the two sorted halves using a temporary buffer.

Merge (Combine) Steps

  1. Copy the entire range [start..end] into a temporary buffer.

  2. Use two pointers: i = start (left sub‑array start) and j = mid+1 (right sub‑array start).

  3. Compare buffer[i] and buffer[j]. Place the smaller into the original array arr[k], increment the respective pointer and k.

  4. When one sub‑array is exhausted, copy the remaining elements from the other sub‑array.

  5. Delete the temporary buffer.

C++ Code Sketch

void mergeSort(int arr[], int s, int e) {
    if (s >= e) return;
    int m = (s + e) / 2;
    mergeSort(arr, s, m);
    mergeSort(arr, m+1, e);
    combine(arr, s, m, e);
}

void combine(int arr[], int s, int m, int e) {
    int* buffer = new int[e-s+1];
    int k = s;
    while (k <= e) {
        buffer[k] = arr[k];
        k++;
    }
    int i = s, j = m+1, k = s;
    while (i <= m && j <= e) {
        if (buffer[i] <= buffer[j]) {
            arr[k] = buffer[i];
            i++;
        } else {
            arr[k] = buffer[j];
            j++;
        }
        k++;
    }
    while (i <= m) {
        arr[k] = buffer[i];
        k++; i++;
    }
    while (j <= e) {
        arr[k] = buffer[j];
        k++; j++;
    }
    delete[] buffer;
}

Time Complexity

  • Best, average, and worst‑case: O(nlog⁡n)O(n \log n)O(nlogn) – consistent performance.

  • Requires O(n)O(n)O(n) extra space for the temporary buffer.

  • Much faster than O(n2)O(n^2)O(n2) algorithms for large arrays.


⏱ Complexity Comparison

Algorithm

Best Case

Average Case

Worst Case

Space

Basic (naive)

O(n2)O(n^2)O(n2)

O(n2)O(n^2)O(n2)

O(n2)O(n^2)O(n2)

O(1)O(1)O(1)

Selection Sort

O(n2)O(n^2)O(n2)

O(n2)O(n^2)O(n2)

O(n2)O(n^2)O(n2)

O(1)O(1)O(1)

Bubble Sort

O(n)O(n)O(n) (optimized)

O(n2)O(n^2)O(n2)

O(n2)O(n^2)O(n2)

O(1)O(1)O(1)

Insertion Sort

O(n)O(n)O(n)

O(n2)O(n^2)O(n2)

O(n2)O(n^2)O(n2)

O(1)O(1)O(1)

Merge Sort

O(nlog⁡n)O(n \log n)O(nlogn)

O(nlog⁡n)O(n \log n)O(nlogn)

O(nlog⁡n)O(n \log n)O(nlogn)

O(n)O(n)O(n)

Merge sort is the only algorithm presented that guarantees O(nlog⁡n)O(n \log n)O(nlogn) time, making it suitable for large datasets.


Summary

  • Simple algorithms (basic, selection, bubble, insertion) are easy to implement but become impractical for large inputs due to O(n2)O(n^2)O(n2) time.

  • Selection sort minimizes swaps but still compares every pair.

  • Bubble sort is intuitive but slow; often used for educational purposes.

  • Insertion sort excels on small or nearly sorted arrays.

  • Merge sort uses divide‑and‑conquer and recursion to achieve O(nlog⁡n)O(n \log n)O(nlogn) performance, though it requires extra memory.

  • Understanding these algorithms builds a foundation for more advanced sorting techniques and algorithm analysis.

The concepts can be implemented in any programming language; C++ is used here for demonstration, but the logic applies directly to Java, Python, C, and others.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent