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 sortingalgorithm 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(",")]
print(bucket_sort(input_elements))
Output:
Enter numbers separated by a comma:
20, 5, 10, 15, 2
[2, 5, 10, 15, 20]
Related Algorithms in Python
- Write a Python program for Linear Search and Binary Search
- Selection Sort Algorithm in Python
- Bubble Sort Algorithm in Python
- Bogo Sort Algorithm in Python
- Bucket Sort Algorithm in Python
- Comb Sort Algorithm in Python
- Counting Sort Algorithm in Python
- Heap Sort Algorithm in Python
- Insertion Sort Algorithm in Python
- Merge Sort Algorithm in Python
- Quick Sort Algorithm in Python
- Shell Sort Algorithm in Python
- Interpolation Search Algorithm in Python
DSA
Python
Comments
Post a Comment