Skip to content

Commit 1ed11b2

Browse files
authoredOct 2, 2022
Added code for bucket sorting techniques
1 parent 2e8fa6c commit 1ed11b2

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
 

‎bucketsort.cpp

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// C++ program to sort an
2+
// array using bucket sort
3+
#include <algorithm>
4+
#include <iostream>
5+
#include <vector>
6+
using namespace std;
7+
8+
// Function to sort arr[] of
9+
// size n using bucket sort
10+
void bucketSort(float arr[], int n)
11+
{
12+
13+
// 1) Create n empty buckets
14+
vector<float> b[n];
15+
16+
// 2) Put array elements
17+
// in different buckets
18+
for (int i = 0; i < n; i++) {
19+
int bi = n * arr[i]; // Index in bucket
20+
b[bi].push_back(arr[i]);
21+
}
22+
23+
// 3) Sort individual buckets
24+
for (int i = 0; i < n; i++)
25+
sort(b[i].begin(), b[i].end());
26+
27+
// 4) Concatenate all buckets into arr[]
28+
int index = 0;
29+
for (int i = 0; i < n; i++)
30+
for (int j = 0; j < b[i].size(); j++)
31+
arr[index++] = b[i][j];
32+
}
33+
34+
/* Driver program to test above function */
35+
int main()
36+
{
37+
float arr[]
38+
= { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 };
39+
int n = sizeof(arr) / sizeof(arr[0]);
40+
bucketSort(arr, n);
41+
42+
cout << "Sorted array is \n";
43+
for (int i = 0; i < n; i++)
44+
cout << arr[i] << " ";
45+
return 0;
46+
}

0 commit comments

Comments
 (0)
Please sign in to comment.