Implementing bubble sort using PHP

Since we are assuming the unsorted number will be in a list, we can use a PHP array to represent the list of unsorted numbers. Since the array has both index and values, we can utilize the array to easily iterate through each item, based on position, and swap them where it is applicable. The code will look like this, based on our pseudocodes:

function bubbleSort(array $arr): array { 
$len = count($arr);

for ($i = 0; $i < $len; $i++) {
for ($j = 0; $j < $len - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$tmp = $arr[$j + 1];
$arr[$j + 1] = $arr[$j];
$arr[$j] = $tmp;
}
}
}
return $arr;
}

As we can see, we are using two for loops to iterate each item and comparing with the rest of the items. The swapping is done in the lines:

$tmp = $arr[$j + 1];
$arr[$j + 1] = $arr[$j];
$arr[$j] = $tmp;

First, we assigned the second value to a temporary variable named $tmp. Then, we assigned the first value to the second value and reassigned the temporary value to the first value. This is known as swapping two variables using a third or temporary variable.

We are only swapping if the first value is greater than the second value. Else, we are just ignoring. The comment on the right-hand side of the image shows whether an exchange occurred or not. If we want to sort it in a descending order (bigger number first), then we can just modify the if condition as follows:

if ($arr[$j] < $arr[$j + 1]) {
}

Now, let's run the code as follows:

$arr = [20, 45, 93, 67, 10, 97, 52, 88, 33, 92]; 
$sortedArray = bubbleSort($arr);
echo implode(",", $sortedArray);

This will produce the following output:

10,20,33,45,52,67,88,92,93,97

So, we can see that the array is sorted using the bubble sort algorithm. Now, let's discuss the complexity of the algorithm.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset