0

General Question: Why is Bucket Sort more beneficial that Quick Sort?

Lets say numbers are incoming from a stream, and my buckets are like (1,10) (11,20) ect ect.

Then I sort the buckets and then put them together, having my sorted numbers.

OR

I can put them in an array, and then sort them with Quicksort

  • Bucket Sort: Bestcase O(N + K) worstcase (N^2);
  • Quicksort: Bestcase O(1) Averagecase O(nlogn) worstcase (N^2);

So why do we use bucket sort for things like streams of incoming integers that we want sorted? Is it because we can make decisions based on the number of integers in each of your buckets?

Thanks

sanmai
  • 23,569
  • 11
  • 54
  • 73
k9b
  • 1,299
  • 4
  • 21
  • 45

1 Answers1

3

If we know k up front, and it is small (k << n) then bucket sort can efficiently run faster than Quicksort, since n*log(n), the average for Quicksort, will be more than (n + k), which is the average for bucket sort.

I.e.,

sortedList = (n*log(n) > n + k) ? bucketSort(list) : quicksort(list);

A reason it may be used for streams, is that bucket sort is in-place. You can maintain the sorted list, adding new elements efficiently, without having to re-sort it every time. You just manipulate the data structure (bucket) directly, and that's it.

Quicksort on the other hand, is not in-place, and requires a full sorting run in order to return the sorted list.

habitats
  • 1,693
  • 2
  • 19
  • 30
  • Thanks a ton! Two more followup questions if you dont mind. 1. So.. If this is a big stream, or a stream in which we are told nothing about the size it may be beneficial to then use Quicksort? 2. Why is it sometimes O(n + k), I've read a couple solutions but it deosnt make as much sense to me as it should – k9b Oct 31 '14 at 02:32
  • please accept the answer if it was satisfactory, btw – habitats Oct 31 '14 at 02:40
  • Yea soz just got back. Thanks for the answer – k9b Oct 31 '14 at 03:01
  • ...What? Quicksort is most certainly in-place. – Louis Wasserman Oct 31 '14 at 05:43
  • Quicksort cannot entirely be done in a single array. – habitats Oct 31 '14 at 10:33
  • BucketSort is not in place. Why you don't count the bucket array?. A reason to be used in streams is because the max char to be ordered compared to the minimum value can be as small as the ASCII value of 0 to the ASCII value of z, hence reducing K to a number around 60 – Alex Mar 09 '15 at 02:05
  • Quicksort is in-place ! There is no allocation of memory in quicksort. The basic implementation of bucketsort on the other hand is not in-place, because the buckets are allocated outside the array. – S. K. Oct 06 '19 at 17:16