What is Bubble Sort?
Bubble sort is a sorting algorithm, It works by comparing each pair of adjacent elements and switching their positions if necessary. It repeats this process until all the elements are sorted.
The average and worst-case time complexity of bubble sort is – O(n2)

Let’s write a PHP code to implement bubble sort algorithm.
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 | // algorithm implementation function bubbleSort(array $arr) { $len = count($arr); for($i = 0; $i < $len-1; $i++) { for($j = 0; $j < $len-$i-1; $j++) { if($arr[$j] > $arr[$j+1]) { $temp = $arr[$j+1]; $arr[$j+1] = $arr[$j]; $arr[$j] = $temp; } } } echo "After Sorting \n"; for($i = 0; $i < $len; $i++) { echo $arr[$i]."\n"; } } //Unsorted array $arr = array(9, 2, 4, 8, 1); //Sort using bubble sort bubbleSort($arr); |