From eb54f6a48f1f38a7720e8bea55cd5f7453d491c7 Mon Sep 17 00:00:00 2001 From: rahulsingh522003 <85445665+rahulsingh522003@users.noreply.github.com> Date: Mon, 31 Oct 2022 09:16:17 +0530 Subject: [PATCH] Create Bucket_sort.cpp --- C++/Bucket_sort.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/Bucket_sort.cpp diff --git a/C++/Bucket_sort.cpp b/C++/Bucket_sort.cpp new file mode 100644 index 0000000..aaa9b26 --- /dev/null +++ b/C++/Bucket_sort.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; + +void bucketSort(int arr[], int n, int k) +{ + int max_val = arr[0]; + for (int i = 1; i < n; i++) + max_val = max(max_val, arr[i]); + + max_val++; + vector bkt[k]; + + for (int i = 0; i < n; i++) + { + int bi = (k * arr[i]) / max_val; + bkt[bi].push_back(arr[i]); + } + + for (int i = 0; i < k; i++) + sort(bkt[i].begin(), bkt[i].end()); + + int index = 0; + for (int i = 0; i < k; i++) + for (int j = 0; j < bkt[i].size(); j++) + arr[index++] = bkt[i][j]; +} + +int main() +{ + int arr[] = {30, 40, 10, 80, 5, 12, 70}; + int n = sizeof(arr) / sizeof(arr[0]); + int k = 4; + bucketSort(arr, n, k); + + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + + return 0; +}