fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. // Bucket Sort in C++
  6. std::vector<double> bucketSort(std::vector<double>& array) {
  7. int n = array.size();
  8. std::vector<std::vector<double>> bucket(n);
  9.  
  10. // Insert elements into their respective buckets
  11. for (int i = 0; i < n; ++i) {
  12. int index_b = static_cast<int>(n * array[i]);
  13. if (index_b >= n) {
  14. index_b = n - 1;
  15. }
  16. bucket[index_b].push_back(array[i]);
  17. }
  18.  
  19. // Sort the elements of each bucket
  20. for (int i = 0; i < n; ++i) {
  21. std::sort(bucket[i].begin(), bucket[i].end());
  22. }
  23.  
  24. // Get the sorted elements
  25. int k = 0;
  26. for (int i = 0; i < n; ++i) {
  27. for (size_t j = 0; j < bucket[i].size(); ++j) {
  28. array[k++] = bucket[i][j];
  29. }
  30. }
  31. return array;
  32. }
  33.  
  34. int main() {
  35. std::vector<double> array = {0.42, 0.32, 0.33, 0.52, 0.37, 0.47, 0.51};
  36. std::cout << "Sorted Array is\n";
  37. std::vector<double> sortedArray = bucketSort(array);
  38.  
  39. for (double val : sortedArray) {
  40. std::cout << val << " ";
  41. }
  42. std::cout << std::endl;
  43.  
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Sorted Array is
0.32 0.33 0.37 0.42 0.47 0.51 0.52