forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShellSort.php
53 lines (44 loc) · 1.03 KB
/
ShellSort.php
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
/**
* Shell Sort
* This function sorts an array in ascending order using the Shell Sort algorithm.
* Time complexity of the Shell Sort algorithm depends on the gap sequence used.
* With Knuth's sequence, the time complexity is O(n^(3/2)).
*
*
* @param array $array
* @return array
*/
function shellSort(array $array): array
{
$length = count($array);
$series = calculateKnuthSeries($length);
foreach ($series as $gap) {
for ($i = $gap; $i < $length; $i++) {
$temp = $array[$i];
$j = $i;
while ($j >= $gap && $array[$j - $gap] > $temp) {
$array[$j] = $array[$j - $gap];
$j -= $gap;
}
$array[$j] = $temp;
}
}
return $array;
}
/**
* Calculate Knuth's series
*
* @param int $n Size of the array
* @return array
*/
function calculateKnuthSeries(int $n): array
{
$h = 1;
$series = [];
while ($h < $n) {
array_unshift($series, $h);
$h = 3 * $h + 1;
}
return $series;
}