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