-
-
Notifications
You must be signed in to change notification settings - Fork 586
Expand file tree
/
Copy pathGnomeSort.php
More file actions
34 lines (30 loc) · 753 Bytes
/
Copy pathGnomeSort.php
File metadata and controls
34 lines (30 loc) · 753 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
declare(strict_types=1);
/**
* 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
*/
function gnomeSort(array $array): array
{
$a = 1;
$b = 2;
while ($a < count($array)) {
if ($array[$a - 1] <= $array[$a]) {
$a = $b;
$b++;
} else {
[$array[$a], $array[$a - 1]] = [$array[$a - 1], $array[$a]];
$a--;
if ($a == 0) {
$a = $b;
$b++;
}
}
}
return $array;
}