2017-09-29 10:25:30 +08:00
|
|
|
// C++ program to sort an array using bucket sort
|
|
|
|
#include <algorithm>
|
2020-05-26 23:46:24 +08:00
|
|
|
#include <iostream>
|
2017-09-29 10:25:30 +08:00
|
|
|
#include <vector>
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2017-09-29 10:25:30 +08:00
|
|
|
// Function to sort arr[] of size n using bucket sort
|
2020-05-26 23:46:24 +08:00
|
|
|
void bucketSort(float arr[], int n) {
|
|
|
|
// 1) Create n empty buckets
|
2020-05-27 00:31:49 +08:00
|
|
|
std::vector<float> *b = new std::vector<float>[n];
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2020-05-26 23:46:24 +08:00
|
|
|
// 2) Put array elements in different buckets
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
|
int bi = n * arr[i]; // Index in bucket
|
|
|
|
b[bi].push_back(arr[i]);
|
|
|
|
}
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2020-05-26 23:46:24 +08:00
|
|
|
// 3) Sort individual buckets
|
|
|
|
for (int i = 0; i < n; i++) std::sort(b[i].begin(), b[i].end());
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2020-05-26 23:46:24 +08:00
|
|
|
// 4) Concatenate all buckets into arr[]
|
|
|
|
int index = 0;
|
|
|
|
for (int i = 0; i < n; i++)
|
|
|
|
for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j];
|
2020-05-27 00:31:49 +08:00
|
|
|
delete[] b;
|
2017-09-29 10:25:30 +08:00
|
|
|
}
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2017-09-29 10:25:30 +08:00
|
|
|
/* Driver program to test above funtion */
|
2020-05-26 23:46:24 +08:00
|
|
|
int main() {
|
|
|
|
float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
|
|
|
|
int n = sizeof(arr) / sizeof(arr[0]);
|
|
|
|
bucketSort(arr, n);
|
2019-08-21 10:10:08 +08:00
|
|
|
|
2020-05-26 23:46:24 +08:00
|
|
|
std::cout << "Sorted array is \n";
|
|
|
|
for (int i = 0; i < n; i++) std::cout << arr[i] << " ";
|
|
|
|
return 0;
|
2017-09-29 10:25:30 +08:00
|
|
|
}
|