It’s very basic stuff. I feel that the code is not concise enough. I hope experts can guide me to modify it.
Copy the code The code is as follows:
php function BubbleSort($str){ for($i=0;$ifor ($k =count($str)-2;$k>=$i;$k--){//Bubble this value forward; if($str[$k+1]<$str[ $k]){ //Change the less than sign to the greater than sign, which is to sort in descending order; $tmp=$str[$k+1]; $str[$k+1]=$str[$ k]; $str[$k]=$tmp; } } } return $str; } //The following is the test $str=array(5,8,2,6,10,0,3,12,11); print_r(BubbleSort($str)); ?>
php bubble sort 2 The basic concept is: compare two adjacent numbers in sequence, put the decimal in the front and the large number in the back. That is, first compare the first and second numbers, put the decimal first and the large number last. Then compare the second number and the third number, put the decimal in front and the large number in the back, and continue like this until comparing the last two numbers, put the decimal in front and the large number in the back. Repeat the above process, still starting from the first pair of numbers (because it may be due to the exchange of the second number and the third number that the first number is no longer smaller than the second number), put the decimal first and the large number first. Finally, compare until a pair of adjacent numbers before the maximum number, put the decimal in front and the large number in the back. The second pass ends and a new maximum number is obtained in the penultimate number. Continue like this until the sorting is finally completed. Because in the sorting process, decimals are always placed forward and large numbers are placed backward, which is equivalent to bubbles rising, so it is called bubble sorting. Implemented using a double loop, with the outer loop variable set to i and the inner loop variable set to j. The outer loop is repeated 9 times, and the inner loop is repeated 9, 8,..., 1 time. The two elements compared each time are related to the inner loop j. They can be identified by a[j] and a[j+1] respectively. The values of i are 1, 2,...,9. For The value of each i, j is 1, 2,...10-i.
PHP bubble sort method demonstration In previous interviews, I felt that the written test questions asked by the examiner were quite XX, and the program should be written on the computer, not on the pen. PHP program file sort_bubble_up.php
http://www.bkjia.com/PHPjc/325904.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325904.htmlTechArticleIt’s very basic. I feel that the code is not concise enough. I hope an expert can guide me to modify and copy the code. The code is as follows: ?php function BubbleSort ($str){ for($i=0;$icount($str);$i++){//Get from the end of the array...
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn