1. First we must figure out what bubble sorting is. If we don’t understand the principle of bubble sorting, we can’t write out code.
BubbleThe basic concept of sorting (BubbleSort) is: compare two adjacent numbers in sequence, put the decimal in the front and the large number in the back. That is, in the first pass: 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. This is the end of the first trip, leaving the largest number at the end. In the second pass: still start the comparison 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 After placing it, the comparison is continued until the second to last number (the first to last position is already the largest). At the end of the second pass, a new maximum number is obtained at the second to last position (in fact, it is the largest number in the entire sequence). The second largest number). Continue like this and repeat the above process until the sorting is finally completed.
PHP implementation code:
<?<span>php </span><span>//</span><span>冒泡排序方法</span> <span>function</span> bubblesort(&<span>$arr</span><span>){ </span><span>//</span><span>定义一个变量保存交换的值</span> <span>$temp</span> =0<span>; </span><span>for</span>(<span>$i</span>=0;<span>$i</span><<span>count</span>(<span>$arr</span>);<span>$i</span>++<span>){ </span><span>for</span>(<span>$j</span>=0;<span>$j</span><<span>count</span>(<span>$arr</span>)-<span>$i</span>-1;<span>$j</span>++<span>){ </span><span>if</span>(<span>$arr</span>[<span>$j</span>]><span>$arr</span>[<span>$j</span>+1<span>]){ </span><span>//</span><span>如果前面的那个数大于后面的那个数,那么他们就进行交换</span> <span>$temp</span>=<span>$arr</span>[<span>$j</span><span>]; </span><span>$arr</span>[<span>$j</span>]=<span>$arr</span>[<span>$j</span>+1<span>]; </span><span>$arr</span>[<span>$j</span>+1]=<span>$temp</span><span>; } } } } </span><span>$arr</span>=<span>array</span>(100,99,200,5,-4,6,-7<span>); bubbleSort(</span><span>$arr</span><span>); </span><span>print_r</span>(<span>$arr</span>); <span>//</span><span>数组是值传递,所以传递的时候加个&符号就是地址传递,改变外部变量</span> ?>