DEV Community

Shahriyar Al Mustakim Mitul
Shahriyar Al Mustakim Mitul

Posted on

DSA by Mitul in C++, Python, and Java : Bucket sort

Here we will create buckets and distribute elements of array into buckets. Sort bucket individually and then merge buckets after sorting.

So, this is the array we are going to sort using bucket sort.

Image description
Lets create some buckets using this law:

Number of buckets= round(sqrt(number of elements))

As we have 9 elements, we will create 3 buckets.Tell me why!

Now we need to decide which number goes to which bucket. Use this formula:
Appropriate bucket=cell(Value*number of buckets*maxValue

Here maxValue is 9.
Now, lets start to find the bucket for number 5 as it is the first number.

Image description

Here Appropriate bucket= cell(5*3/9)==2
as the value was 5. Bucket we have 3 and maxValue=9 , we get appropriate bucket for 5 is the number 2 bucket.

Image description

We have moved it to the bucket 2.
For the number 3, we have:

Image description

For the number 4, we have:

Image description

Thus the process follows like this:

Image description

It goes on and on. Finally we have:

Image description

Now let;s sort each bucket using any of our choice(You can use any algorithm to sort a particular bucket).

Image description

After 3 buckets are sorted, we have:

Image description

Now we need to add values from bucket to the main array. First we will use bucket 1

Image description

Then 2nd one:

Image description

then 3rd one:

Image description

Finally, we have

Image description

Code for Bucket sort

def bucketSort(customList):
    numberofBuckets = round(math.sqrt(len(customList)))
    maxValue = max(customList)
    arr = []

    for i in range(numberofBuckets):
        arr.append([])
    for j in customList:
        index_b = math.ceil(j*numberofBuckets/maxValue)
        arr[index_b-1].append(j)

    for i in range(numberofBuckets):
        arr[i] = insertionSort(arr[i])

    k = 0
    for i in range(numberofBuckets):
        for j in range(len(arr[i])):
            customList[k] = arr[i][j]
            k += 1
    return customList
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Image description

When to use Bucket Sort?

  1. When input uniformly distributed over range. That means there is not a huge gap between values in the list.

Image description

When to avoid Bucket sort?
When space is a concern.

Top comments (0)