TheAlgorithms-PHP/Sorting/GnomeSort.php

34 lines
738 B
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Gnome Sort
* References:
* https://www.geeksforgeeks.org/gnome-sort-a-stupid-one/
*
* The Gnome algorithm works by locating the first instance in which two adjoining elements are arranged incorrectly and swaps with each other.
*
* @param array $array refers to the array to be sorted
* @return array
*/
function gnomeSort($array)
{
$a = 1;
$b = 2;
while ($a < count($array)) {
if ($array[$a - 1] <= $array[$a]) {
$a = $b;
$b++;
} else {
list($array[$a],$array[$a - 1]) = array($array[$a - 1],$array[$a]);
$a--;
if ($a == 0) {
$a = $b;
$b++;
}
}
}
return $array;
}