Bubble Sort Algorithm in PHP

Bubble Sort Algorithm in PHP

17/05/2023
43 Lượt xem

Sorting is a crucial task in data management as it allows us to quickly search for information. However, when it comes to web programming, we often rely on built-in sorting functions provided by PHP, which are convenient. But since we are learning programming, you shouldn't overlook the fundamental knowledge of sorting algorithms.

In this article, we will explore the simplest sorting algorithm, which is the Bubble Sort algorithm. The idea behind this algorithm is to compare adjacent elements and swap them if they are in the wrong order. We can proceed from left to right or from right to left, depending on our preference.

Note: For ease of explanation, I will refer to $n as the total number of elements in the array, and 1 as the position of the first element in the array (although arrays start from index 0, I will use 1 to make it more intuitive).

1. Bubble Sort in Ascending Order

The Bubble Sort algorithm in ascending order is processed as follows:

For the loop $i running from 1 to ($n-1):

Iteration 1: $i = 1, sequentially compare with other positions starting from ($i + 1), which is position 2. If the first element is greater than the elements following it starting from 2, swap them.

Iteration 2: $i = 2, sequentially compare with other positions starting from ($i + 1), which is position 3. If the second element is greater than the elements following it starting from 3, swap them.

Continue this process until we iterate the ($n-1)th time, where $i = ($n-1). Now we compare with the last element ($n) and swap if it does not satisfy the condition.

Example: Given the array: $array = array(1, 5, 9, 2, 4, 9), use the Bubble Sort algorithm to sort the array in ascending order.

This array has 6 elements starting from 0 to 5. Therefore, we have the following solution:

<?php
	$array = array(1, 5, 9, 2, 4, 9); // array given in the problem
	  
	$length = 6; // or use $length = count($array);
	  
	// Sort the array
	for ($i = 0; $i < ($length - 1); $i++){
	    for ($j = $i + 1; $j < $length; $j++){ // iterate over elements after $i
	        if ($array[$i] > $array[$j]){ // if element $i is greater than the subsequent element
	            // swap
	            $tmp = $array[$j];
	            $array[$j] = $array[$i];
	            $array[$i] = $tmp;
	        }
	    }
	}

	// Display the sorted array elements
	for ($i = 0; $i < $length; $i++){
	    echo $array[$i] . ' ';
	}
?>

In this code, we use nested for loops to iterate over the elements. For each iteration of $i, we use a $j loop to iterate from the next position ($i + 1) to the end of the array. If the elements are not in the correct order, we swap them.

You might wonder about the use of swapping and the $tmp variable. Imagine you are holding a heavy bag with both hands, and your father is holding a heavy chair with both hands as well. Now, you want to exchange these two items, meaning you will give the bag to your father, and your father will give you the chair. But how can you perform this exchange? The solution is to have an intermediary person hold the bag for you temporarily, then your father can give you the chair, and after that, your father takes the bag from the intermediary person. Based on this analogy, in the code snippet, we use the $tmp variable as an intermediary storage to facilitate the swapping process.

2. Bubble sort in descending order

The idea of bubble sort in descending order is similar to the ascending order. The only difference is that when comparing two elements, if the $i-th element is smaller than the ($i + 1)-th element, we swap their positions. Using the given example, the solution is as follows:

<?php
	$array = array(1, 5, 9, 2, 4, 9); // array as given in the problem

	$length = 6; // or you can use $length = count($array);

	// Sort the array
	for ($i = 0; $i < ($length - 1); $i++){
	    for ($j = $i + 1; $j < $length; $j++){ // loop through the elements after $i
	        if ($array[$i] < $array[$j]){ // if element $i is smaller than the element after it
	            // swap
	            $tmp = $array[$j];
	            $array[$j] = $array[$i];
	            $array[$i] = $tmp;
	        }
	    }
	}

	// Display the sorted elements of the array
	for ($i = 0; $i < $length; $i++){
	    echo $array[$i] . ' ';
	}
?>

3. Putting the Bubble Sort Algorithm into a Function

I have a question: why did we code in such an unprofessional way when we have learned about creating functions in PHP? To make the program more scalable and manageable for maintenance, let’s put the sorting code into a function.

<?php
	// Sorting function
	function bubble_sort_asc($array){
	    $length = count($array);
	    
	    // Sort the array
	    for ($i = 0; $i < ($length - 1); $i++){
	        for ($j = $i + 1; $j < $length; $j++){
	            if ($array[$i] > $array[$j]){
	                // Swap
	                $tmp = $array[$j];
	                $array[$j] = $array[$i];
	                $array[$i] = $tmp;
	            }
	        }
	    }
	    
	    return $array;
	}
	  
	// Display function
	function display_array($array){
	    $length = count($array);
	    for ($i = 0; $i < $length; $i++){
	        echo $array[$i] . ' ';
	    }
	}
	  
	//--------------------------------------------------
	// Main program
	$array = array(1, 5, 9, 2, 4, 9); // array as given in the problem
	  
	// Sort the array
	$array = bubble_sort_asc($array);
	  
	// Display the array
	display_array($array);
?>

4. Conclusion

The Bubble Sort algorithm in PHP is simple and easy to implement, making it widely used in programming courses at universities for introductory data structure subjects. In this lesson, we stop here, and in the next lesson, we will explore the Linear Search algorithm in PHP.

Rate this series
Download and Install Vertrigo Server
17/05/2023
43 Lượt xem
Operators and expressions in PHP
17/05/2023
43 Lượt xem
The if else statement in PHP
17/05/2023
43 Lượt xem
The switch case statement in PHP
17/05/2023
43 Lượt xem
The for loop in PHP
17/05/2023
43 Lượt xem
While and do-while loops in PHP
17/05/2023
43 Lượt xem
The foreach Loop in PHP
17/05/2023
43 Lượt xem
Building Functions in PHP
17/05/2023
43 Lượt xem
Recursive Algorithm in PHP
17/05/2023
43 Lượt xem
Bubble Sort Algorithm in PHP
17/05/2023
43 Lượt xem
Linear Search Algorithm in PHP
17/05/2023
43 Lượt xem
The technique of sentry placement in PHP
17/05/2023
43 Lượt xem
Flagging technique in PHP
17/05/2023
43 Lượt xem
Selection Sort Algorithm in PHP
17/05/2023
43 Lượt xem

Related Articales

Comments

© copyright 2021 Courseplus