#include <iostream>
#include <vector>
// A simple function to print a sequence of values.
// Keeping printing separate makes main() cleaner.
void print_values(const std::vector<int>& values) {
for (int v : values) {
std::cout << v << " ";
}
std::cout << "\n";
}
// Sort the array using a single-loop variant of "gnome sort".
// This algorithm walks forward, but whenever it finds two adjacent
// elements out of order, it swaps them and steps back by one.
// Because the index moves both forward and backward inside the same loop,
// we don't need nested loops.
//
// This approach is expressive, easy to follow, and uses only one loop.
// It is not the fastest algorithm for large datasets, but it is efficient
// enough for small to medium inputs and demonstrates the technique clearly.
void single_loop_sort(std::vector<int>& values) {
std::size_t i = 0;
int size = values.size();
// One loop only.
while (i < size) {
// If we're at the beginning or the current pair is in order,
// move forward.
if (i == 0 || values[i] >= values[i - 1]) {
++i;
} else {
// Otherwise, swap the out-of-order pair.
std::swap(values[i], values[i - 1]);
// Step back to re-check previous relationships.
--i;
}
}
}
int main() {
std::vector<int> values {42, -5, 12, 0, 89, -18, 33, 7};
std::cout << "Original values:\n";
print_values(values);
// Perform the single-loop sort
single_loop_sort(values);
std::cout << "Sorted values:\n";
print_values(values);
}
/*
run:
Original values:
42 -5 12 0 89 -18 33 7
Sorted values:
-18 -5 0 7 12 33 42 89
*/