Data Structure and Algorithm
This article is part of series in Data Structure and Algorithm:
In this tutorial, we will learn a simple sorting algorithm - Bubble Sort.
Table Of Content
1. Problem to Solve
Given a list of numbers as shown below, please sort them in ascending order.
- You are required to use Bubble Sort algorithm when sorting the numbers.
- You are required to implement the algorithm in PHP language.
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:
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.
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.