Implementations in C++ and C
suggest changeAn in-place C++ implementation using modern range constraints:
#include <algorithm>
#include <concepts>
#include <functional>
#include <ranges>
template<std::ranges::random_access_range Range,
class Compare = std::ranges::less>
requires std::sortable<std::ranges::iterator_t<Range>, Compare>
void bubble_sort(Range&& values, Compare compare = {}) {
auto end = std::ranges::end(values);
while (end != std::ranges::begin(values)) {
bool swapped = false;
for (auto current = std::ranges::begin(values), next = current + 1;
next != end; ++current, ++next) {
if (std::invoke(compare, *next, *current)) {
std::ranges::iter_swap(current, next);
swapped = true;
}
}
if (!swapped) return;
--end;
}
}
C Implementation
#include <stdbool.h>
#include <stddef.h>
void bubble_sort(long values[], size_t length) {
while (length > 1) {
bool swapped = false;
for (size_t index = 1; index < length; ++index) {
if (values[index - 1] > values[index]) {
const long temporary = values[index - 1];
values[index - 1] = values[index];
values[index] = temporary;
swapped = true;
}
}
if (!swapped) return;
--length;
}
}
Array indexing and pointer arithmetic are equivalent in C. The indexed form above is generally easier to read and does not need a duplicate implementation.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents