Skip to content

Commit

Permalink
Merge pull request #18 from Raman1309/patch-3
Browse files Browse the repository at this point in the history
BucketSort.cpp
  • Loading branch information
nayyyhaa authored Oct 27, 2019
2 parents 0f0749f + 363c371 commit 543415d
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions BucketSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

// Function to sort arr[] of size n using bucket sort
void bucketSort(float arr[], int n)
{
// 1) Create n empty buckets
vector<float> b[n];

// 2) Put array elements in different buckets
for (int i=0; i<n; i++)
{
int bi = n*arr[i]; // Index in bucket
b[bi].push_back(arr[i]);
}

// 3) Sort individual buckets
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());

// 4) Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
}

/* Driver program to test above funtion */
int main()
{
int n;
cout<<"\n Size : ";
cin>>n;

float arr[n];
cout<<"\n Enter elements in array : ";
for(int i=0;i<n;i++)
cin>>arr[i];

bucketSort(arr, n);

cout << "Sorted array is \n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}

0 comments on commit 543415d

Please sign in to comment.