-
Notifications
You must be signed in to change notification settings - Fork 0
/
bucketSort.cpp
90 lines (77 loc) · 1.86 KB
/
bucketSort.cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* @file bucketSort.cpp
* @author your name ([email protected])
* @brief
* @version 0.1
* @date 2023-03-10
*
* @copyright Copyright (c) 2023
*
*/
#include <iostream>
#include <limits>
#include <utility>
#include <vector>
#include <algorithm>
static int n, arr[1000];
void Initialization();
void BucketSort();
void Display();
int main() {
Initialization();
BucketSort();
Display();
}
void Initialization()
{
std::cin >> n;
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
}
void BucketSort() {
int max{INT_MIN}, min{INT_MAX};
float range;
for(int i = 0; i < n; i++) {
if(arr[i] > max) max = arr[i];
if(arr[i] < min) min = arr[i];
}
range = (max - min) / n;
std::vector<std::vector<int> > temp;
// create empty buckets
for (int i = 0; i < n; i++) {
temp.push_back(std::vector<int>());
}
// scatter the array elements into the correct bucket
for (int i = 0; i < n; i++) {
double diff = (arr[i] - min) / range - int((arr[i] - min) / range);
// append the boundary elements to the lower array
if (diff == 0 && arr[i] != min) {
temp[int((arr[i] - min) / range) - 1].push_back(arr[i]);
}
else {
temp[int((arr[i] - min) / range)].push_back(arr[i]);
}
}
// Sort each bucket individually
for (int i = 0; i < n; i++) {
if (!temp[i].empty()) {
sort(temp[i].begin(), temp[i].end());
}
}
// Gather sorted elements to the original array
int k = 0;
for (int i=0; i < n; i++) {
if (!temp[i].empty()) {
for (int j = 0; j < temp[i].size(); j++) {
arr[k] = temp[i][j];
k++;
}
}
}
}
void Display() {
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
}