TheAlgorithms-PHP/Sorting/GnomeSort.php
TKF486 c97dadec46 Created new sort algorithm
added gnome sort algorithm, with added unit tests and updated DIRECTORY.md
2022-08-03 16:40:30 +08:00

35 lines
728 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;
}