Sorting & Searching
Implementing algorithms in C teaches you how sorting, searching, and recursion work at the lowest level — no library magic, just pointers and memory.
40 min•By Priygop Team•Last updated: Feb 2026
Algorithm Implementations
Example
#include <stdio.h>
// Binary search (array must be sorted)
int binarySearch(int arr[], int size, int target) {
int low = 0, high = size - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1; // Not found
}
// Quicksort
void swap(int *a, int *b) {
int t = *a; *a = *b; *b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
quicksort(arr, 0, n - 1);
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
// Output: 11 12 22 25 64
int index = binarySearch(arr, n, 22);
printf("\nFound 22 at index %d\n", index); // 2
return 0;
}Big-O Complexity
- O(1) — Constant: array access, hash table lookup. Same speed regardless of input size
- O(log n) — Logarithmic: binary search. Halves the problem each step. Very fast for large datasets
- O(n) — Linear: linear search, single loop. Time grows proportionally with input
- O(n log n) — Linearithmic: merge sort, quicksort (average). Best general-purpose sorting
- O(n²) — Quadratic: bubble sort, nested loops. Slow for large inputs. Avoid for n > 10,000
- O(2ⁿ) — Exponential: recursive fib, brute force. Impractical for n > 30