0% completed
Bucket Sort is a comparison-based sorting algorithm that distributes elements into several 'buckets'. Each bucket is then sorted individually, either using another sorting algorithm or recursively applying the bucket sort. Finally, the sorted buckets are concatenated to form the final sorted array. This algorithm is particularly effective when the input is uniformly distributed over a range.
Bucket Sort works in the following steps:
Bucket Sort can achieve a linear time complexity of O(n) in the best case scenario, where the elements are uniformly distributed. However, in the worst case, when all elements fall into the same bucket, the time complexity can degrade to O(n log n).
Initialize Buckets:
numBuckets = sqrt(n)
.Distribute Elements into Buckets:
num
in the array, calculate the bucket index as bucketIndex = (num * numBuckets) / (maxVal + 1)
.buckets[bucketIndex]
.Sort Each Bucket:
Collections.sort
in Java).Concatenate Buckets:
Input: array1 = {29, 25, 3, 49, 9, 37, 21, 43, 45}
Initialize Buckets:
numBuckets = sqrt(9) ≈ 3
.buckets = [[], [], []]
.Distribute Elements into Buckets:
Find the maximum value: maxVal = 49
.
Calculate the bucket index and place each element into its corresponding bucket:
29
: bucketIndex = (29 * 3) / 50 ≈ 1
. Place 29
into buckets[1]
.25
: bucketIndex = (25 * 3) / 50 ≈ 1
. Place 25
into buckets[1]
.3
: bucketIndex = (3 * 3) / 50 ≈ 0
. Place 3
into buckets[0]
.49
: bucketIndex = (49 * 3) / 50 ≈ 2
. Place 49
into buckets[2]
.9
: bucketIndex = (9 * 3) / 50 ≈ 0
. Place 9
into buckets[0]
.37
: bucketIndex = (37 * 3) / 50 ≈ 2
. Place 37
into buckets[2]
.21
: bucketIndex = (21 * 3) / 50 ≈ 1
. Place 21
into buckets[1]
.43
: bucketIndex = (43 * 3) / 50 ≈ 2
. Place 43
into buckets[2]
.45
: bucketIndex = (45 * 3) / 50 ≈ 2
. Place 45
into buckets[2]
.After distribution, buckets
look like:
buckets[0] = [3, 9]
buckets[1] = [29, 25, 21]
buckets[2] = [49, 37, 43, 45]
Sort Each Bucket:
buckets[0]
becomes [3, 9]
.buckets[1]
becomes [21, 25, 29]
.buckets[2]
becomes [37, 43, 45, 49]
.Concatenate Buckets:
array = [3, 9, 21, 25, 29, 37, 43, 45, 49]
.Creating Buckets: Initializing buckets takes O(n) time.
Distributing Elements into Buckets: This takes O(n) time.
Sorting Each Bucket:
Collections.sort()
) takes O(k log k) time, where k is the number of elements in a bucket.Concatenating Buckets:
Overall Time Complexity:
Overall Space Complexity: O(n), which includes the original array and the buckets.
Sorting Floating Point Numbers
Data Distribution Analysis
Digital Signal Processing
Parallel Processing
External Sorting
.....
.....
.....