This article is mainly for everyone to introduce the PHP implementation of the bucket sorting algorithm, with a certain reference value, interested in small partners can refer to, hope to help everyone.
Bucket sort in simple sense:
The principle of bucket sorting is to arrange n+1 buckets as containers first, if the data range is n.
The test data (the data to be sorted) is then looped and placed in the corresponding bucket. The data must be within the range N.
Finally, the elements in the loop are recycled, and the output is sorted from large to small or from smallest to largest.
For example:
Our value range is 10, then we need to define a 11-length array $arr. And let all the element values be 0
The array that needs to be sorted is then looped as 5,3,5,2,8. (This way the value range is actually only 8)
The data in turn corresponds to the elements in the $arr bucket array, that is, if it is 5, then $arr[5]++.
At this time $arr [2]=1 $arr [3]=1 $arr [5]=2 $arr [8]=1
Then loop the array of $arr, if $arr[2]=1, then loop the output element 21 times, $arr [5]=2, then loop output 52 times
The resulting output is 2 3 5 5 8
If the loop value is from large to small, it is sorted from large to small
<?php//set default array, default value is 0, $arr = Array (), for ($i = 0; $i <=; $i + +) {$arr [$i] = 0;} Set the five data of the test $ARR1 = Array (5, 3, 5, 2, 8);//The corresponding element of the default array is +1 according to the data; The value range of J cannot be equal to the $ARR1 array length for ($j = 0; $j < count ($arr 1); $j + +) {//side to the corresponding array value +1 $arr [$arr 1[$j]]++;} Start looping output default array $arr the corresponding value for ($k = 0; $k <=; $k + +) {for ($l =1; $l <= $arr [$k]; $l + +) { echo "$k </n>"; }}?>
Disadvantages:
Wasted space.
Unable to sort floating-point data.