Copy code The code is as follows:
$arr = array(345,4,17,6,52,16,58,69,32,8,234);
for($i=1;$i< count($arr);$i++){
for($j=count($arr)-1;$j>=$i;$j--){
if($arr[$j]<$arr [$j-1]){
$temp = $arr[$j-1];
$arr[$j-1] = $arr[$j];
$arr[$j] = $temp;
}
}
}
Basic concept
The basic concept of bubble sort is: compare two adjacent numbers in sequence, put the decimal in front and the large number in the back. That is, first compare the 1st and 2nd numbers, put the decimals first and the large numbers 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 greater than the second number), put the decimal first and the large number first. Finally, compare until a pair of adjacent numbers before the smallest number, put the decimal in front and the large number in the back. The second pass ends and a new minimum 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.
Use a double loop to implement, the outer loop variable is set to i, and the inner loop variable is 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 in order. For each The values of i and j are 1,2,…10-i in sequence.
Generate
In many programming, we need to sort a sequence to facilitate statistics. Common sorting methods include bubble sort, binary tree sort, selection sort, etc. Bubble sorting has always been popular due to its concise thinking method and relatively high efficiency.
Sorting process
Imagine that the sorted array R [1..N] is erected vertically, and each data element is regarded as a weighted bubble. According to the principle that light bubbles cannot be under heavy bubbles, the array R is scanned from bottom to top. , whenever a light bubble that violates this principle is scanned, it will be "floated" upward, and this process is repeated until the last two bubbles are the lighter one at the top and the heavier one at the bottom.
Update 2009-8-18: Error in updating code.
The above introduces the implementation code of bubble sorting PHP bubble sorting algorithm, including the content of bubble sorting. I hope it will be helpful to friends who are interested in PHP tutorials.