Bucket Sort

Bucket Sort

Algorithm Steps

  1. Divide the input array into a finite number of buckets.
  2. Distribute the elements of the array into these buckets based on a given range.
  3. Sort each non-empty bucket individually (using another sorting algorithm or recursively applying bucket sort).
  4. Concatenate the sorted buckets to obtain the final sorted array.

Bucket Sort Program Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
def bucket_sort(arr):
    n = len(arr)
    if n == 0:
        return arr
    # Create n empty buckets
    buckets = [[] for _ in range(n)]
    # Put array elements in different buckets
    for num in arr:
        index = int(num * n) if num < 1 else n - 1
        buckets[index].append(num)
    # Sort individual buckets and concatenate
    sorted_arr = []
    for bucket in buckets:
        sorted_arr.extend(sorted(bucket))
    return sorted_arr

if __name__ == '__main__':
    arr = [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51]
    sorted_arr = bucket_sort(arr)
    print("Sorted array is:", sorted_arr)