Description: Bucket sort is a distribution sorting algorithm that divides the elements of an array into several "buckets." Each bucket is then sorted individually, either using a different sorting algorithm or recursively applying bucket sort. The sorted buckets are then concatenated to produce the final sorted array.
Here's a C++ implementation of bucket sort:
#include <iostream>
#include <vector>
#include <algorithm> // For std::sort
using namespace std;
// Function to perform bucket sort
void bucketSort(vector<float>& arr) {
int n = arr.size();
if (n <= 0) return;
// Create n empty buckets
vector<vector<float>> buckets(n);
// Put array elements into their respective buckets
for (float num : arr) {
int bucketIndex = n * num; // Assuming num is in range [0, 1)
buckets[bucketIndex].push_back(num);
}
// Sort each bucket and concatenate results
for (int i = 0; i < n; i++) {
sort(buckets[i].begin(), buckets[i].end());
}
// Clear the original array
arr.clear();
// Concatenate all sorted buckets
for (const auto& bucket : buckets) {
for (float num : bucket) {
arr.push_back(num);
}
}
}
int main() {
vector<float> arr = {0.42, 0.32, 0.23, 0.52, 0.31, 0.55, 0.87, 0.19};
bucketSort(arr);
cout << "Sorted array: ";
for (float num : arr) {
cout << num << " ";
}
cout << endl;
return 0;
}
bucketSort function takes a vector of floats as input.n * num assumes that the input is normalized to the range .sort function.Bucket sort is particularly useful for sorting uniformly distributed data over a range. Its average-case time complexity of makes it efficient for large datasets when the number of buckets is proportional to the number of elements. However, its performance can degrade if the data is not uniformly distributed or if too few buckets are used. Despite this, bucket sort can be a powerful sorting technique when applied in the right contexts, especially in combination with other sorting algorithms for bucket sorting.
Open this section to load past papers