Skip to content

Commit 908f075

Browse files
mulirowMohamad655
authored andcommitted
Added bucketsort.cpp
1 parent 956979d commit 908f075

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
//Bucket sort is an effiicent way of sorting numbers between 0.0 and 1.0.
6+
7+
//Algorithm:
8+
void bucketSort(float array[], int n){
9+
vector<float> bucket[n];
10+
int k = 0;
11+
12+
for(int i = 0; i < n; i++){
13+
int x = n*array[i];
14+
bucket[x].push_back(array[i]);
15+
}
16+
17+
for(int i = 0; i < n; i++){
18+
sort(bucket[i].begin(), bucket[i].end());
19+
20+
}
21+
22+
for(int i = 0; i < n; i++){
23+
for (int j = 0; j < bucket[i].size(); j++){
24+
array[k] = bucket[i][j];
25+
k++;
26+
}
27+
}
28+
}
29+
30+
//Test:
31+
int main(){
32+
int n;
33+
float array[] = {0.182, 0.429, 0.18, 0.02, 0.912, 0.586, 0.129, 0.911};
34+
n = sizeof(array) / sizeof(array[0]);
35+
cout << "Elements before bucket sort:\n";
36+
for (int i = 0; i < n; i++){
37+
cout << array[i] << " ";
38+
}
39+
cout << "\n";
40+
41+
bucketSort(array, n);
42+
43+
cout << "Elements after bucket sort:\n";
44+
for(int i = 0; i < n; i++){
45+
cout << array[i] << " ";
46+
}
47+
cout << "\n";
48+
}

0 commit comments

Comments
 (0)