Bucket Sorting
Explanation of bucket sorting
Simple Version
To start with, assuming we have this set of numbers and we want to sort it in inscending order:
1 |
|
1 |
|
To use bucket sort to finish this task, firstly we need to build buckets to contain the numbers. Note that the amount of buckets depends on the range of set:
Then for each number in the set, we compare it with the number on each bucket from left to right, if they are same, the amount of number in the bucket increase by 1:
After we have put all numbers in the corresponding buckets, we travel buckets from left to right to see how many numbers in each buckets and pick them out one by one. The numbers are sorted:
Universal Version
In the last version, we have a empty bucket unused which causes waste of money. How can we avoid this kind of waste?
We can not save it completly, but we can improve the use efficency of buckets. Consider that the number on each bucket is a range instead of certain number:
In this case, for each number in the set, we compare it with the range on each bucket from left to right, if the number is contains in the range, put the number in the bucket. Note that the numbers in the buckets must keep inscending order(can use insertion sort, another is also ok):
Then we travel buckets from left to right to see how many numbers in each buckets and pick them out in order. The numbers are sorted:
You may notice that the choice of range is important. If the range is too small, the space cost is large. If the range is too large, the time cost is large.
Pros and cons of bucket sorting
Pros
- The time complexity is about O(n). The exact one is O( n* m ), m is the time complexity of the sort inside the bucket. The efficiency is high.
Cons
- When the data is not homogenous, the efficiency decrease. If the data is exact concertrate, the bucket sort may decrease to the sort inside the bucket.
- A bad choice of range can also cause the efficiency decrease or the waste of space. The algorithm is sensed to choice of range.
Implementation
Python
1 |
|
Java
1 |
|
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!