Skip to content

Instantly share code, notes, and snippets.

@matusstafura
Created January 19, 2023 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matusstafura/7b049a323624a99a9f0120492888621e to your computer and use it in GitHub Desktop.
Save matusstafura/7b049a323624a99a9f0120492888621e to your computer and use it in GitHub Desktop.
Bubble sort in PHP
<?php
function bubbleSort(array $a): array
{
for ($i = count($a) - 1; $i > 0; $i--) {
for ($j = 0; $j < $i; $j++) {
if ($a[$j] > $a[$j + 1]) {
$temp = $a[$j];
$a[$j] = $a[$j+1];
$a[$j+1] = $temp;
}
}
}
return $a;
}
// $bs = [5, 2, 8, 9, 1];
// bubbleSort($bs);
// [1, 2, 5, 8, 9]
function bubbleSortOptimized(array $a): array
{
for ($i = count($a) - 1; $i > 0; $i--) {
$swap = false;
for ($j = 0; $j < $i; $j++) {
if ($a[$j] > $a[$j + 1]) {
$temp = $a[$j];
$a[$j] = $a[$j+1];
$a[$j+1] = $temp;
$swap = true;
}
}
if (!$swap) break;
}
return $a;
}
// $bs = [6, 1, 2, 3, 4, 5];
// bubbleSortOptimized($bs);
// [1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment