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