Data Structure and Algorithm - Bubble Sort
Table Of Content
1. Problem to Solve
Given a list of numbers as shown below, please sort them in ascending order.
1
| $numbers = [21,25,100,98,89,77]; |
Requirements:
- You are required to use Bubble Sort algorithm when sorting the numbers.
- You are required to implement the algorithm in PHP language.
2. Pseudocode
Bubble Sort works by comparing two values at a time and does it pair by pair. And it iterates until all elements are in place. After each iteration, at least one element is moved to the end of the list. Below is an illustration of the first iteration.

Pseudocode of Bubble Sort algorithm can be written as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
| FOR each element of the list FOR each element of the list IF current element greater then next element swap the elements END IF END FOREND FOR |
The inner loop is considered one iteration and the outer loop makes sure we iterate enough times to sort the list.
3. PHP Implementation
To implement Bubble Sort in PHP, all we need is two loops. Note that the termination of both loops is: the length of the list - 1. This is to prevent from accessing un-indexed element.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| <?php$numbers = [21, 25, 100, 98, 89, 77];for ($i = 0; $i < (count($numbers) - 1); $i++) { for ($j = 0; $j < (count($numbers) - 1); $j++) { if ($numbers[$j] > $numbers[$j + 1]) { $tmp = $numbers[$j]; $numbers[$j] = $numbers[$j + 1]; $numbers[$j + 1] = $tmp; } }}print_r($numbers);// Output:/*Array( [0] => 21 [1] => 25 [2] => 77 [3] => 89 [4] => 98 [5] => 100)*/ |
4. The End
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.
Comments
Post a Comment