PHP implementation bubble Sort, PHP bubble sort
1, first we must understand what is bubble sort, do not understand the principle of bubble sort, we can not write code.
The basic concept of a bubbling sort (bubblesort) is to compare the adjacent two numbers in turn, place decimals in front, and large numbers behind. That is, in the first trip: first compare the 1th and 2nd numbers, put the decimals before the large number. Then compare the 2nd and 3rd numbers, place the decimal before the large number, and then continue until you compare the last two numbers, put the decimals before the decimal, and put the large number behind. At the end of the first trip, the largest number was put to the last. In the second pass: The comparison is still starting from the first logarithm (because the 1th number is no longer less than the 2nd number due to the 2nd and 3rd number of interchanges), before the decimal, the large number is placed, it is compared to the second-to-last number (which is already the largest in the penultimate position), the second trip ends, Get a new maximum number in the penultimate position (actually the second largest number in the whole sequence). So go on, repeat the above process until the final sort is finished.
PHP Implementation code:
Php//Bubble Sort Method functionBubblesort (&$arr){ //define a variable to hold the value of the interchange $temp=0; for($i= 0;$i<Count($arr);$i++){ for($j= 0;$j<Count($arr)-$i-1;$j++){ if($arr[$j]>$arr[$j+1]){ //If the previous number is greater than the number in the back, then they exchange it . $temp=$arr[$j]; $arr[$j]=$arr[$j+1]; $arr[$j+1]=$temp; } } } } $arr=Array(100,99,200,5,-4,6,-7); Bubblesort ($arr); Print_r($arr);//An array is a value pass, so adding a & symbol when passing it is address passing, changing the external variable?>
http://www.bkjia.com/PHPjc/1129315.html www.bkjia.com true http://www.bkjia.com/PHPjc/1129315.html techarticle PHP Implementation bubble sort, php bubble sort 1, first we have to figure out what is bubble sort, do not understand the principle of bubble sort, we can not write code. Bubble sort (bubbl ...