Learning Algorithms is a great way to improve your coding skills. In this project, I cover how to code a Bubble Sort Algorithm in PHP. This algorithm is a basic demonstration of how to use various aspects of PHP to accomplish a specific task. I will be demonstrating how to use Variables, Loops, Functions, if Conditionals and more in this tutorial.
Why should you learn algorithms? While PHP and other languages already have sorting functions that do the heavy lifting for you, learning how to code your own algorithms will give you a deeper understanding of how to code. You can also learn how to refactor or optimize your code by using various techniques.
First Video Code Snippet
The code snippet below is for the final project. Make sure to watch the video in order to get a step by step tutorial.
<?php
$arr = [ 16, 5, 13, 7, 19, 18, 1, 30 ];
function bubbleSort( $arr ) {
$length = count( $arr );
$comparisons = 0;
for ( $i = 0; $i < $length; $i++ ) {
for ( $j = 0; $j < $length - 1; $j++ ) {
$comparisons++;
if ( $arr[ $j ] > $arr[ $j + 1 ] ) {
$tmp = $arr[ $j + 1 ];
$arr[ $j + 1 ] = $arr[ $j ];
$arr[ $j ] = $tmp;
} // end of if conditional
} // end of inner for loop
} // end of first for loop
echo '<h4>' . $comparisons . ' Comparisons</h4>';
return $arr;
} // end of bubbleSort()
echo '<strong>Before Sorting</strong><br>' . implode( ', ', $arr ) . '<br>';
$sorted = bubbleSort( $arr );
echo '<strong>After Sorting</strong><br>' . implode( ', ', $sorted );
Second Video Code Snippet
The code below is for the refactored version of our Bubble Sort Algorithm
<?php
$arr = [ 16, 5, 13, 7, 19, 18, 1, 30 ];
function bubbleSort( $arr ) {
$length = count( $arr );
$boundary = $length - 1;
$comparisons = 0;
for ( $i = 0; $i < $length; $i++ ) {
$swapped = false;
$newBoundary = 0;
for ( $j = 0; $j < $boundary; $j++ ) {
$comparisons++;
if ( $arr[ $j ] > $arr[ $j + 1 ] ) {
$tmp = $arr[ $j + 1 ];
$arr[ $j + 1 ] = $arr[ $j ];
$arr[ $j ] = $tmp;
$swapped = true;
$newBoundary = $j;
} // end of if conditional
} // end of inner for loop
$boundary = $newBoundary;
if ( !$swapped ) {
break;
}
} // end of first for loop
echo '<h4>' . $comparisons . ' Comparisons</h4>';
return $arr;
} // end of bubbleSort()
echo '<strong>Before Sorting</strong><br>' . implode( ', ', $arr ) . '<br>';
$sorted = bubbleSort( $arr );
echo '<strong>After Sorting</strong><br>' . implode( ', ', $sorted );