Bucket Sort Algorithm in Python

In this source code example, we will write a code to implement the Bucket Sort algorithm in Python.

Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting
algorithm or by recursively applying the bucket sorting algorithm. It is a distribution sort and is a cousin of the radix sort in the most to least significant digit flavor.

Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons and therefore can also be considered a comparison sort algorithm. The computational complexity estimates involve the number of buckets.

Bucket Sort Algorithm in Python

In this Python program, we will take input from the User or console and print the result to the output:
def bucket_sort(my_list: list) -> list:
    if len(my_list) == 0:
        return []
    min_value, max_value = min(my_list), max(my_list)
    bucket_count = int(max_value - min_value) + 1
    buckets: list[list] = [[] for _ in range(bucket_count)]

    for i in my_list:
        buckets[int(i - min_value)].append(i)

    return [v for bucket in buckets for v in sorted(bucket)]

if __name__ == "__main__":
    user_input = input("Enter numbers separated by a comma:\n").strip()
    input_elements = [int(item) for item in user_input.split(",")]


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course