Open In App

Bucket Sort in Python

Last Updated : 15 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Bucket sort is a sorting technique that involves dividing elements into various groups, or buckets. These buckets are formed by uniformly distributing the elements. Once the elements are divided into buckets, they can be sorted using any other sorting algorithm. Finally, the sorted elements are gathered together in an ordered fashion.

Bucket Sort Algorithm:

  • Create an array of empty buckets.
  • Iterate through the input array and distribute each element into the corresponding bucket based on some criteria.
  • Sort each bucket individually (using another sorting algorithm or recursively applying bucket sort).
  • Concatenate all the sorted buckets to get the final sorted array.

How does Bucket Sort work?

To apply bucket sort on the input array [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68], we follow these steps:

  • Step 1: Create an array of size 10, where each slot represents a bucket.
  • Step 2: Insert elements into the buckets from the input array based on their range.
  • Step 3: Sort the elements within each bucket. In this example, we use quicksort (or any stable sorting algorithm) to sort the elements within each bucket.
  • Step 4: Gather the elements from each bucket and put them back into the original array.
  • Step 5: The original array now contains the sorted elements.

The final sorted array using bucket sort for the given input is [0.12, 0.17, 0.21, 0.23, 0.26, 0.39, 0.68, 0.72, 0.78, 0.94].

Implementation of Bucket Sort in Python:

Below is the implementation of bucket sort in python:

Python3
def insertion_sort(bucket):
    for i in range(1, len(bucket)):
        key = bucket[i]
        j = i - 1
        while j >= 0 and bucket[j] > key:
            bucket[j + 1] = bucket[j]
            j -= 1
        bucket[j + 1] = key

def bucket_sort(arr):
    n = len(arr)
    buckets = [[] for _ in range(n)]

    # Put array elements in different buckets
    for num in arr:
        bi = int(n * num)
        buckets[bi].append(num)

    # Sort individual buckets using insertion sort
    for bucket in buckets:
        insertion_sort(bucket)

    # Concatenate all buckets into arr[]
    index = 0
    for bucket in buckets:
        for num in bucket:
            arr[index] = num
            index += 1

arr = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68]
bucket_sort(arr)
print("Sorted array is:")
print(" ".join(map(str, arr)))

Output
Sorted array is:
0.12 0.17 0.21 0.23 0.26 0.39 0.68 0.72 0.78 0.94

Complexity Analysis of Bucket Sort Algorithm:

Time Complexity: O(n2),

  • If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time.
  • The O(1) is easily possible if we use a linked list to represent a bucket.
  • Step 4 also takes O(n) time as there will be n items in all buckets. 
  • The main step to analyze is step 3. This step also takes O(n) time on average if all numbers are uniformly distributed.

Auxiliary Space: O(n+k)


Similar Reads

Tag sort or Bucket sort or Bin sort in Python
Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in the input array to determine the range of tags ne
2 min read
Radix Sort vs Bucket Sort
We have two standard sorting algorithms, named bucket sort and radix sort. They both share differences and similarities. Let’s explore some similarities, differences, advantages, and disadvantages here in more detail. Bucket Sort: Bucket sort is a sorting algorithm in which the elements are separated into several groups that are called buckets. Eac
6 min read
Bucket Sort To Sort an Array with Negative Numbers
We have discussed bucket sort in the main post on Bucket Sort . Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the problem of sorting a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. In the above post, we have discussed Buck
9 min read
Bucket Sort vs Quick Sort
Bucket Sort and Quick Sort are two different sorting algorithms, each with its own characteristics, advantages, and disadvantages. In this article, we will provide a detailed overview of all the differences between Bucket Sort and Quick Sort. Bucket Sort:Bucket Sort is a non-comparison sorting algorithm that divides the input array into a number of
3 min read
Bucket Sort Visualization Using Javascript
GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Bucket Sort using JavaScript. We will see how the elements are stored in Buckets and then how Buckets get traversed to get the final sorted array. We will also visualize the time complexity of Bucket Sort. Refer: Bucket SortAsynchronous Fun
7 min read
Minimum number of pigs required to find the poisonous bucket
Given an integer N denoting the number of buckets, and an integer M, denoting the minimum time in minutes required by a pig to die after drinking poison, the task is to find the minimum number of pigs required to figure out which bucket is poisonous within P minutes, if there is exactly one bucket with poison, while the rest is filled with water. E
5 min read
Minimize the Maximum Number of Balls in a Bucket
Given an array arr[] and a positive integer K, where arr[i] represent number of balls in the ith bucket. The task is to minimize the maximum number of balls in a bucket by performing operation at most K times. The operation is to take any bucket and divide it into two new buckets with a positive number of balls in it. For example, a bucket of 5 bal
7 min read
Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
C/C++ Program for Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i
2 min read
Java Program for Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i
2 min read
Article Tags :
three90RightbarBannerImg