PHP implementation Bucket Sorting

Source: Internet
Author: User

Today re-look at the bucket sorting, the idea is relatively simple, here to tidy up, lest forget next time.

Suppose you want to sort a set of data 2 2 3 1 6 5 4.

1. First select the minimum element 1 and the maximum element 6, make a bucket, that is, define an array of 1-6, and set their values to 0.

2. Traversing this bucket, each step of the bucket in the array to find whether there are elements and the bucket subscript is equal, if so, then the value of the corresponding element in the bucket is increased by 1;

3. Traversing a bucket, the number of occurrences of an element in a bucket in the array can be ordered, and an array is used to save the result and return it.

The code is as follows:

1<?PHP2 3 $list=Array(2,2,3,1,6,5,4);4 5 functionBacketsort ($list){6     $min=min($list);7     $max=Max($list);8     //make buckets, minimum to maximum value all with 0 padding9     $arr=Array_fill($min,$max-$min+1,0);Ten     //into the barrel One     foreach($list  as $k=$v){ A         $arr[$v]++; -     } -  the     foreach($arr  as $k=$v){ -          for($i= 1;$i<=$v;$i++){ -             $result[] =$k; -         } +     } -     return $result; + } A  at $list= Backetsort ($list); -  - Var_dump($list);

PHP implementation Bucket Sorting

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.