PHP implementation Bucket sorting algorithm example sharing

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.