fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. // Function to sort arr[] of size n using bucket sort
  7. void bucketSort(float arr[], int n)
  8. {
  9. // 1) Create n empty buckets
  10. vector<float> b[n];
  11.  
  12. // 2) Put array elements in different buckets
  13. for (int i=0; i<n; i++)
  14. {
  15. int bi = n*arr[i]; // Index in bucket
  16. b[bi].push_back(arr[i]);
  17. }
  18.  
  19. // 3) Sort individual buckets
  20. for (int i=0; i<n; i++)
  21. sort(b[i].begin(), b[i].end());
  22.  
  23. // 4) Concatenate all buckets into arr[]
  24. int index = 0;
  25. for (int i = 0; i < n; i++)
  26. for (int j = 0; j < b[i].size(); j++)
  27. arr[index++] = b[i][j];
  28. }
  29.  
  30. /* Driver program to test above funtion */
  31. int main()
  32. {
  33. float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
  34. int n = sizeof(arr)/sizeof(arr[0]);
  35. bucketSort(arr, n);
  36.  
  37. cout << "Sorted array is \n";
  38. for (int i=0; i<n; i++)
  39. cout << arr[i] << " ";
  40. return 0;
  41. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Sorted array is 
0.1234 0.3434 0.565 0.656 0.665 0.897