Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d912095

Browse files
BucketSort.cpp
This solves fnplus#243
1 parent 63b8d0c commit d912095

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /