From bdfa4e1576178eed3347de84bf203043702ca54d Mon Sep 17 00:00:00 2001 From: Satyam Singh <56315878+satcasm@users.noreply.github.com> Date: Wed, 3 Feb 2021 20:35:35 +0530 Subject: [PATCH] added bucket & counting sort in cpp (#57) * add binary search in js * added merge sort in c * added quick sort in cpp * modified quick sort * added heap sort * updated readme.md * added counting sort * added bucket sort --- sorting/README.md | 1 + sorting/c-or-cpp/bucket-sort.cpp | 40 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 sorting/c-or-cpp/bucket-sort.cpp diff --git a/sorting/README.md b/sorting/README.md index 514d5c1d..4c14a06b 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -9,6 +9,7 @@ 5. [Quick Sort](c-or-cpp/quick-sort.cpp) 6. [Heap Sort](c-or-cpp/heap-sort.cpp) 7. [Counting Sort](c-or-cpp/counting-sort.cpp) +8. [Bucket Sort](c-or-cpp/bucket-sort.cpp) ### C# diff --git a/sorting/c-or-cpp/bucket-sort.cpp b/sorting/c-or-cpp/bucket-sort.cpp new file mode 100644 index 00000000..31f4fbe5 --- /dev/null +++ b/sorting/c-or-cpp/bucket-sort.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace std; +void bucketSort(float a[], int n); + +// Driver Code +int main() +{ + float a[] = {0.971, 0.565, 0.420, 0.123, 0.315, 0.696}; + int n = sizeof(a) / sizeof(a[0]); + cout << "Original array:\n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + bucketSort(a, n); + cout << "\nSorted array:\n"; + for (int i = 0; i < n; i++) + cout << a[i] << " "; + return 0; +} + +void bucketSort(float a[], int n) +{ + // Create n empty buckets + vector b[n]; + //Put array elements in different buckets + for (int i = 0; i < n; i++) + { + int ib = n * a[i]; // Index in bucket + b[ib].push_back(a[i]); + } + //Sort individual buckets + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + //Concatenate all buckets into a[] + int in = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + a[in++] = b[i][j]; +} \ No newline at end of file