Sunday, August 6, 2023

Bucket Sort in C++

 A simple program to demonstrate the concepts of bucket sort algorithm in C++ programming language.

I am currently accepting programming work, IT projects, school and application development, programming projects, thesis and capstone projects, IT consulting work, computer tutorials, and web development work kindly contact me at the following email address for further details.  If you want to advertise on my website kindly contact me also in my email address also. Thank you.

My email address is the following jakerpomperada@gmail.com, jakerpomperada@aol.com, and jakerpomperada@yahoo.com.

My mobile number here in the Philippines is 09173084360.

Please subscribe to my channel  https://www.youtube.com/channel/UCOs-lpOoIeJoh6gpJthPoGg

=================================================


You can buy my C++ book online at  


https://www.mindshaperspublishing.com/product/beginners-guide-to-c-programming/


You can buy my book in introduction to computer networking at 

https://www.unlimitedbooksph.com/product-page/introduction-to-computer-networking


Want to support my channel?

GCash Account

Jake Pomperada




09173084360


Paypal

https://paypal.me/jakerpomperada


Patreon

https://www.patreon.com/jakerpomperada


Thank you very much for your support.




Program Listing

#include <iostream> #include <vector> #include <algorithm> // Function to perform Bucket Sort void bucketSort(std::vector<float>& arr) { int n = arr.size(); // Create buckets and initialize them as empty lists std::vector<std::vector<float>> buckets(n); // Place elements in their respective buckets for (int i = 0; i < n; ++i) { int bucketIndex = n * arr[i]; buckets[bucketIndex].push_back(arr[i]); } // Sort individual buckets using any sorting algorithm (e.g., insertion sort) for (int i = 0; i < n; ++i) { std::sort(buckets[i].begin(), buckets[i].end()); } // Concatenate sorted buckets to obtain the final sorted array int index = 0; for (int i = 0; i < n; ++i) { for (float num : buckets[i]) { arr[index++] = num; } } } int main() { std::vector<float> arr = {0.4, 0.1, 0.6, 0.9, 0.2, 0.7}; std::cout <<"\n\n\tBucket Sort in C++\n\n"; std::cout << "Original Array: "; for (float num : arr) { std::cout << num << " "; } std::cout << std::endl; std::cout <<"\n\n"; bucketSort(arr); std::cout << "Sorted Array: "; for (float num : arr) { std::cout << num << " "; } std::cout << std::endl; return 0; }

No comments:

Post a Comment