Home > Article > Backend Development > How to implement bubble sort algorithm in php
Bubble sort algorithm is a basic sorting algorithm and one of the simplest sorting algorithms. Its principle is very simple, it is to repeatedly traverse the array that needs to be sorted, and compare two adjacent elements each time. If their order is wrong, swap them until the largest element is found, and then repeat the above operation. Until the entire array is sorted.
The following is how to implement the bubble sort algorithm in PHP:
$array = array(5, 3, 8, 1, 6, 7, 2, 4);
function bubble_sort($array) { $count = count($array); for($i=0;$i<$count-1;$i++) { for($j=0;$j<$count-$i-1;$j++) { if($array[$j]>$array[$j+1]) { $temp = $array[$j]; $array[$j] = $array[$j+1]; $array[$j+1] = $temp; } } } return $array; }
$result = bubble_sort($array); print_r($result);
The complete code is as follows:
$array = array(5, 3, 8, 1, 6, 7, 2, 4); function bubble_sort($array) { $count = count($array); for($i=0;$i<$count-1;$i++) { for($j=0;$j<$count-$i-1;$j++) { if($array[$j]>$array[$j+1]) { $temp = $array[$j]; $array[$j] = $array[$j+1]; $array[$j+1] = $temp; } } } return $array; } $result = bubble_sort($array); print_r($result);
The output results are as follows:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )
The above is the complete method of implementing the bubble sort algorithm in PHP.
The above is the detailed content of How to implement bubble sort algorithm in php. For more information, please follow other related articles on the PHP Chinese website!