Skip to content

Commit

Permalink
Adding Bucket Sort in C++ (#46)
Browse files Browse the repository at this point in the history
* Adding Bucket Sort in C++

* Update README.md
  • Loading branch information
echace13 authored Oct 10, 2022
1 parent 7bdb17d commit 68105d4
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions C++/bucketsort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// C++ program to sort an
// array using bucket sort
#include <algorithm>
#include <iostream>
#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 function */
int main()
{
float arr[]
= { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 };
int n = sizeof(arr) / sizeof(arr[0]);
bucketSort(arr, n);

cout << "Sorted array is \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Language
├─ binarysearch.
├─ binarytree.
├─ bubblesort.
├─ bucketsort.
├─ checkPrime.
├─ eval.
├─ fibonacci.
Expand Down

0 comments on commit 68105d4

Please sign in to comment.