PHP randomly picks one algorithm". Today we will continue to explain to you the relevant knowledge points of the common PHP algorithm series, namely PHP Bubble Sorting Algorithm.
Bubble sorting, I believe is no stranger to programmers. To put it simply, the bubble sort algorithm compares two adjacent numbers in sequence, and then sorts them according to size until the last two digits. The reason why it is called the "bubble sort" algorithm is because larger elements will slowly "float" to the top of the array through exchange (arranged in ascending or descending order), just like the bubbles of carbon dioxide in carbonated drinks. It will eventually float to the top.PHP bubble sorting algorithm based on specific code examples. (The following is the ascending order, that is, from small to large)
The code example is as follows:
<?php function maopao($arr){ $len = count($arr); for($k=0;$k<=$len;$k++) { for($j=$len-1;$j>$k;$j--){ if($arr[$j]<$arr[$j-1]){ $temp = $arr[$j]; $arr[$j] = $arr[$j-1]; $arr[$j-1] = $temp; } } } return $arr; } $arr = [2,6,2,8,2,34,5,9,2341,23]; var_dump(maopao($arr));
Note: Here we store the value of $j through the temporary variable $temp medium, so as to compare two adjacent elements in a loop and put the larger value at the end.
Output:array (size=10) 0 => int 2 1 => int 2 2 => int 2 3 => int 5 4 => int 6 5 => int 8 6 => int 9 7 => int 23 8 => int 34 9 => int 2341
PHP Bubble Sort Algorithm (2)", we will use XdebugDebug the implementation process of running the bubble sort algorithm more intuitively for everyone.
The above is the detailed content of PHP bubble sort algorithm (1). For more information, please follow other related articles on the PHP Chinese website!