Created
January 19, 2023 09:09
-
-
Save matusstafura/7b049a323624a99a9f0120492888621e to your computer and use it in GitHub Desktop.
Bubble sort in PHP
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 | |
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