Skip to content

Instantly share code, notes, and snippets.

@matusstafura
Last active March 15, 2024 10:33
Show Gist options
  • Save matusstafura/09c0af86c749f5e5066f920d44f31ba1 to your computer and use it in GitHub Desktop.
Save matusstafura/09c0af86c749f5e5066f920d44f31ba1 to your computer and use it in GitHub Desktop.
Selection Sort in PHP
<?php
function selectionSort(array $a): array
{
for ($i = 0; $i < count($a) - 1; $i++) {
$min_i = $i;
for ($j = $i + 1; $j < count($a); $j++) {
if ($a[$j] < $a[$min_i]) {
$min_i = $j;
}
}
if ($i != $min_i) {
$temp = $a[$i];
$a[$i] = $a[$min_i];
$a[$min_i] = $temp;
}
}
return $a;
}
// $a = [5, 1, 4, 3];
// selectionSort($a);
// [1, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment