-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucket_sort_v2.cpp
More file actions
44 lines (33 loc) · 973 Bytes
/
Copy pathbucket_sort_v2.cpp
File metadata and controls
44 lines (33 loc) · 973 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// This program implements the bucket sort algorithm to sort an array of floating-point numbers.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void bucketSort(vector<float>& arr) {
int n = arr.size();
if (n <= 0) return;
float maxVal = *max_element(arr.begin(), arr.end());
vector<vector<float>> buckets(n);
for (float num : arr) {
int index = static_cast<int>(n * num / maxVal);
if (index == n) index--;
buckets[index].push_back(num);
}
for (int i = 0; i < n; i++) {
sort(buckets[i].begin(), buckets[i].end());
}
auto it = arr.begin();
for (int i = 0; i < n; i++) {
it = copy(buckets[i].begin(), buckets[i].end(), it);
}
}
int main() {
int n;
cin >> n;
vector<float> array(n);
for (int i = 0; i < n; i++) cin >> array[i];
bucketSort(array);
for (float num : array) cout << num << " ";
cout << endl;
return 0;
}