Last active
May 29, 2016 08:53
-
-
Save esase/4f5fd5ad5de24afb5fc5a067a9dcab72 to your computer and use it in GitHub Desktop.
Selection sort [algorithm]
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
<?php | |
/** | |
* Selection sort | |
* | |
* @param array $input | |
* @return array | |
*/ | |
function selectionSort(array $input) | |
{ | |
// get count of items | |
$itemsCount = count($input); | |
// process item | |
for($i = 0; $i < $itemsCount; $i++) { | |
$minValue = $input[$i]; | |
$minIndex = $i; | |
// find a minimum value | |
for($j = $i + 1; $j < $itemsCount; $j++) { | |
if ($input[$j] < $minValue) { | |
$minValue = $input[$j]; | |
$minIndex = $j; | |
} | |
} | |
if ($input[$i] > $minValue) { | |
// swap values | |
list($input[$i], $input[$minIndex]) = [$minValue, $input[$i]]; | |
} | |
} | |
return $input; | |
} | |
// tests | |
$testCases = [ | |
[ | |
'input' => [6, 5, 1, 3, 8, 4, 7, 9, 2], | |
'expect' => '1 2 3 4 5 6 7 8 9' | |
], | |
[ | |
'input' => [2, 0, -1], | |
'expect' => '-1 0 2' | |
], | |
[ | |
'input' => [2, 0, 1, 0], | |
'expect' => '0 0 1 2' | |
], | |
[ | |
'input' => [2, 0, 1, 0], | |
'expect' => '0 0 1 2' | |
], | |
[ | |
'input' => [1, 0, 0, 4], | |
'expect' => '0 0 1 4' | |
], | |
[ | |
'input' => [3, 2, 1, 0], | |
'expect' => '0 1 2 3' | |
], | |
[ | |
'input' => [3, 2, 1, 0, 4], | |
'expect' => '0 1 2 3 4' | |
], | |
[ | |
'input' => [0, 1, -1, 5, -2], | |
'expect' => '-2 -1 0 1 5' | |
], | |
[ | |
'input' => [5, 8, 0, -1, 0, 9, 5, -2], | |
'expect' => '-2 -1 0 0 5 5 8 9' | |
], | |
]; | |
foreach ($testCases as $case) { | |
$result = implode(' ', selectionSort($case['input'])); | |
if ($case['expect'] == $result) { | |
echo '<span style="color:green">passed:</span> ' . $case['expect'] . ' == ' . $result; | |
} | |
else { | |
echo '<span style="color:red">failed:</span> ' . $case['expect'] . ' <>' . $result; | |
} | |
echo '<br />'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment