-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbucket_sort.cpp
More file actions
60 lines (50 loc) · 1.33 KB
/
bucket_sort.cpp
File metadata and controls
60 lines (50 loc) · 1.33 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
void insertion_sort(vector<float> &vec)
{
int len = vec.size();
for (int i = 1; i < len; i++)
{
float key = vec[i];
int j = i - 1;
while (j >= 0 && vec[j] > key)
{
vec[j + 1] = vec[j];
j--;
}
vec[j + 1] = key;
}
}
void bucket_sort(vector<float> &vec, int len)
{
float max_value = *max_element(vec.begin(), vec.end());
float min_value = *min_element(vec.begin(), vec.end());
int num_bucket = 10;
vector<vector<float>> buckets(num_bucket);
// inserting the elements in the buckets
for (auto num : vec)
{
// finding the index of the number in the buckets
int num_index = static_cast<int>((num - min_value) * (num_bucket - 1) / (max_value - min_value));
buckets[num_index].push_back(num);
}
// clearing the elements of the vector to store the sorted elements
vec.clear();
for (auto &bucket : buckets)
{
insertion_sort(bucket);
vec.insert(vec.end(), bucket.begin(), bucket.end());
}
}
int main()
{
vector<float> vec = {0.35, 0.12, 0.43, 0.15, 0.04, 0.50, 0.132};
int len = vec.size();
bucket_sort(vec, len);
for (int i = 0; i < len; i++)
{
cout << vec[i] << " ";
}
cout << endl;
return 0;
}