C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
bubble_sort.c
Go to the documentation of this file.
1/**
2 * @file bubble_sort.c
3 * @brief Bubble sort with early-exit optimization.
4 *
5 * Repeatedly walk the array, swapping adjacent out-of-order pairs.
6 * If a full pass produced no swaps the array is sorted — bail early.
7 * Stable, O(n²) worst, O(n) best.
8 */
9
10#include "sorts.h"
11#include <stdbool.h>
12#include <string.h>
13
14void bubble_sort_strings(char **arr, size_t n) {
15 if (n <= 1) return;
16 for (size_t i = 0; i < n - 1; i++) {
17 bool swapped = false;
18 for (size_t j = 0; j < n - 1 - i; j++) {
19 if (strcmp(arr[j], arr[j + 1]) > 0) {
20 char *tmp = arr[j];
21 arr[j] = arr[j + 1];
22 arr[j + 1] = tmp;
23 swapped = true;
24 }
25 }
26 if (!swapped) return;
27 }
28}
29
30void bubble_sort_ints(int *arr, size_t n) {
31 if (n <= 1) return;
32 for (size_t i = 0; i < n - 1; i++) {
33 bool swapped = false;
34 for (size_t j = 0; j < n - 1 - i; j++) {
35 if (arr[j] > arr[j + 1]) {
36 int tmp = arr[j];
37 arr[j] = arr[j + 1];
38 arr[j + 1] = tmp;
39 swapped = true;
40 }
41 }
42 if (!swapped) return;
43 }
44}
void bubble_sort_ints(int *arr, size_t n)
Definition bubble_sort.c:30
void bubble_sort_strings(char **arr, size_t n)
Definition bubble_sort.c:14
Unified header for all sorting algorithms.