C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
insertion_sort.c
Go to the documentation of this file.
1/**
2 * @file insertion_sort.c
3 * @brief Insertion sort — stable, O(n²) worst, O(n) on nearly-sorted input.
4 *
5 * Walk the array left-to-right; for each element, slide it leftward over
6 * any larger predecessors until it lands in its sorted slot.
7 */
8
9#include "sorts.h"
10#include <string.h>
11
12void insertion_sort_strings(char **arr, size_t n) {
13 if (n <= 1) return;
14 for (size_t i = 1; i < n; i++) {
15 char *key = arr[i];
16 size_t j = i;
17 while (j > 0 && strcmp(arr[j - 1], key) > 0) {
18 arr[j] = arr[j - 1];
19 j--;
20 }
21 arr[j] = key;
22 }
23}
24
25void insertion_sort_ints(int *arr, size_t n) {
26 if (n <= 1) return;
27 for (size_t i = 1; i < n; i++) {
28 int key = arr[i];
29 size_t j = i;
30 while (j > 0 && arr[j - 1] > key) {
31 arr[j] = arr[j - 1];
32 j--;
33 }
34 arr[j] = key;
35 }
36}
void insertion_sort_ints(int *arr, size_t n)
void insertion_sort_strings(char **arr, size_t n)
Unified header for all sorting algorithms.