From 7f5dc34f5ed2953f64d4eaef6e218580aca9b39b Mon Sep 17 00:00:00 2001 From: SashiPraba Date: Sat, 17 Oct 2020 11:55:57 +0800 Subject: [PATCH] added bucketsort in c++ --- Algorithms/Algorithms/bucketSort.cpp | 42 ++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Algorithms/Algorithms/bucketSort.cpp diff --git a/Algorithms/Algorithms/bucketSort.cpp b/Algorithms/Algorithms/bucketSort.cpp new file mode 100644 index 0000000..e8778fb --- /dev/null +++ b/Algorithms/Algorithms/bucketSort.cpp @@ -0,0 +1,42 @@ +// C++ program to sort an array using bucket sort +#include +#include +#include +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 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]; +} + + +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; +} +