/**
* Sorts an array in-place in non-decreasing order using Gnome Sort.
*
* Algorithm Logic (Single Loop):
* - Advances through the array using a single while loop index.
* - Moves forward when adjacent elements are in correct relative order.
* - When an out-of-order adjacent pair is encountered, swaps the elements
* and steps backward one index to verify order against preceding items.
* - Time Complexity: O(N) best case (already sorted), O(N^2) worst case.
* - Space Complexity: O(1) auxiliary space.
*
* @param array<int|float|string> &$arr The array to be sorted in place (passed by reference).
*/
function singleLoopSort(array &$arr): void
{
$pos = 0;
$len = count($arr);
while ($pos < $len) {
// Move forward if at the beginning or if the current pair is sorted
if ($pos === 0 || $arr[$pos] >= $arr[$pos - 1]) {
$pos++;
} else {
// Swap adjacent out-of-order elements using symmetric array destructuring
[$arr[$pos], $arr[$pos - 1]] = [$arr[$pos - 1], $arr[$pos]];
$pos--;
}
}
}
/**
* Main
*/
function main(): void
{
$numbers = [42, -5, 12, 0, 89, -18, 33, 7];
echo "Original array:\n";
echo implode(' ', $numbers) . "\n";
singleLoopSort($numbers);
echo "\nSorted array:\n";
echo implode(' ', $numbers) . "\n";
}
main();
/*
run:
Original array:
42 -5 12 0 89 -18 33 7
Sorted array:
-18 -5 0 7 12 33 42 89
*/