Skip to content

Instantly share code, notes, and snippets.

@esase
Last active May 29, 2016 08:57
Show Gist options
  • Save esase/2e3c5bb609ec9e1acf8743c827e30ad8 to your computer and use it in GitHub Desktop.
Save esase/2e3c5bb609ec9e1acf8743c827e30ad8 to your computer and use it in GitHub Desktop.
Insertion sort [algorithm] [problem at: https://www.hackerrank.com/challenges/insertionsort2]
<?php
/**
* Insertion sort
*
* @param array $input
* @return array
*/
function insertionSort(array $input)
{
// get count of items
$itemsCount = count($input);
// process items
for ($i = 0; $i < $itemsCount; $i++) {
for($j = $i; $j >= 0; $j--) {
if (isset($input[$j - 1]) && $input[$j] < $input[$j - 1]) {
// swap values
list($input[$j], $input[$j - 1]) = [$input[$j - 1], $input[$j]];
}
}
}
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(' ', insertionSort($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