Created
March 28, 2012 20:46
-
-
Save nmmmnu/2230380 to your computer and use it in GitHub Desktop.
Improved Shell Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
function shell_sort($a){ | |
$step = count($a) - 1; | |
while ( true ){ | |
$sorted = false; | |
echo sprintf("Step %3d\n", $step); | |
while ( ! $sorted ){ | |
$sorted = true; | |
for ($i = 0; $i < count($a); $i++) | |
echo sprintf("[ %4d ] ", $a[$i]); | |
echo "\n"; | |
for ($i = 0; $i < count($a) - $step; $i++){ | |
$j = $i + $step; | |
if ($a[$i] > $a[$j]){ | |
$tmp = $a[$i]; | |
$a[$i] = $a[$j]; | |
$a[$j] = $tmp; | |
$sorted = false; | |
} | |
} | |
} | |
if ($sorted && $step == 1) | |
break; | |
$step = (int) ($step / 2 + 0.5); | |
// $step = (int) ($step / 2); | |
if ($step < 1) | |
$step = 1; | |
} | |
return $a; | |
} | |
$a = array(324,23,2,35,6,333,224,6555,23,2,4,78); | |
print_r(shell_sort($a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Step 11
[ 324 ] [ 23 ] [ 2 ] [ 35 ] [ 6 ] [ 333 ] [ 224 ] [ 6555 ] [ 23 ] [ 2 ] [ 4 ] [ 78 ]
[ 78 ] [ 23 ] [ 2 ] [ 35 ] [ 6 ] [ 333 ] [ 224 ] [ 6555 ] [ 23 ] [ 2 ] [ 4 ] [ 324 ]
Step 6
[ 78 ] [ 23 ] [ 2 ] [ 35 ] [ 6 ] [ 333 ] [ 224 ] [ 6555 ] [ 23 ] [ 2 ] [ 4 ] [ 324 ]
[ 78 ] [ 23 ] [ 2 ] [ 2 ] [ 4 ] [ 324 ] [ 224 ] [ 6555 ] [ 23 ] [ 35 ] [ 6 ] [ 333 ]
Step 3
[ 78 ] [ 23 ] [ 2 ] [ 2 ] [ 4 ] [ 324 ] [ 224 ] [ 6555 ] [ 23 ] [ 35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