Skip to content
AgileLogics
6 min read

Sorting & Searching Algorithms

Prerequisites: Recursion

Implementing these by hand in C — with no built-in .sort() to reach for — makes clear what a higher-level language's sort is actually doing underneath.

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int binarySearch(int arr[], int n, int target) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == target) return mid;
        if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1; // not found
}

Binary search requires a sorted array, and roughly halves the search space on every step — dramatically faster than checking every element for large arrays. The standard library's own qsort (<stdlib.h>) is a production-quality sort worth reaching for in real code, once the concept behind it is understood.