Skip to content

Commit bb41d7e

Browse files
authored
bucket sort algorithm added
1 parent 433661f commit bb41d7e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

bucketsort.cpp

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

0 commit comments

Comments
 (0)