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:
istarts at 0,jstarts ati+1.For each
i, iteratejfromi+1to 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
ireaches 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 → swap2and1→[1, 3, 2, 5].i=0, j=3:
5 < 1? No.i=1, j=2:
2 < 3? Yes → swap3and2→[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) – due to nested loops.
Best‑case: 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
ifrom0ton-2:Call a helper function
locationOfSmallest(array, i, n-1)to find the index of the minimum element in the subarray fromito the end.Swap
array[i]witharray[minIndex]using a swap function.
Key Functions
swap(array, x, y): exchangesarray[x]andarray[y].locationOfSmallest(array, start, end): returns the index of the smallest element in the range[start, end]. It iterates fromstarttoendand tracks the smallest value.
Visual Example
Initial array: [5, 4, 3, 7, 9]
i=0: Find smallest in
[0..4]→ value3at index2. Swap5and3→[3, 4, 5, 7, 9].i=1: Find smallest in
[1..4]→ value4at index1(already in place). No swap.i=2: Find smallest in
[2..4]→ value5at index2. 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) comparisons; but only 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-1down to1:Compare
array[i]andarray[i-1]. Ifarray[i] < array[i-1], swap them.
After one full pass, the smallest element moves to the beginning.
Repeat for
n-1passes; 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
3and4→4heavier, stay.Compare
1and5→ swap →[3,1,5,4,3]Compare
5and3→ etc. After full pass, smallest1at front.
Pass 2: Next smallest
3moves 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).
Best‑case (already sorted): 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 (index0) 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
keyatarray[j+1].
Visual Example: [3, 7, 9, 4]
i=1:
key = 7. Sorted part[3].3 < 7→ no shift. Insert7after3:[3,7,9,4].i=2:
key = 9. Sorted part[3,7].7 < 9,3 < 9→ no shift. Insert9:[3,7,9,4].i=3:
key = 4. Sorted part[3,7,9]. Compare9 > 4→ shift9right →[3,7,9,9]. Compare7 > 4→ shift7right →[3,7,7,9]. Compare3 > 4? No → stop. Insertkeyat index1:[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) – every element shifts through the entire sorted part.
Best‑case (already sorted): O(n) – no shifts needed.
Average‑case: 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
2and3→2placed, increment left index.Compare
4and3→3placed, increment right index.Continue:
4vs8→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 (
starttomid) and right half (mid+1toend).Merge the two sorted halves using a temporary buffer.
Merge (Combine) Steps
Copy the entire range
[start..end]into a temporarybuffer.Use two pointers:
i = start(left sub‑array start) andj = mid+1(right sub‑array start).Compare
buffer[i]andbuffer[j]. Place the smaller into the original arrayarr[k], increment the respective pointer andk.When one sub‑array is exhausted, copy the remaining elements from the other sub‑array.
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(nlogn) – consistent performance.
Requires O(n) extra space for the temporary buffer.
Much faster than O(n2) algorithms for large arrays.
⏱ Complexity Comparison
Algorithm | Best Case | Average Case | Worst Case | Space |
|---|---|---|---|---|
Basic (naive) | O(n2) | O(n2) | O(n2) | O(1) |
Selection Sort | O(n2) | O(n2) | O(n2) | O(1) |
Bubble Sort | O(n) (optimized) | O(n2) | O(n2) | O(1) |
Insertion Sort | O(n) | O(n2) | O(n2) | O(1) |
Merge Sort | O(nlogn) | O(nlogn) | O(nlogn) | O(n) |
Merge sort is the only algorithm presented that guarantees 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) 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(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.