TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bucket_sort.cpp
1// C++ program to sort an array using bucket sort
2#include <algorithm>
3#include <iostream>
4#include <vector>
5
6// Function to sort arr[] of size n using bucket sort
7void bucketSort(float arr[], int n) {
8 // 1) Create n empty buckets
9 std::vector<float> *b = new std::vector<float>[n];
10
11 // 2) Put array elements in different buckets
12 for (int i = 0; i < n; i++) {
13 int bi = n * arr[i]; // Index in bucket
14 b[bi].push_back(arr[i]);
15 }
16
17 // 3) Sort individual buckets
18 for (int i = 0; i < n; i++) std::sort(b[i].begin(), b[i].end());
19
20 // 4) Concatenate all buckets into arr[]
21 int index = 0;
22 for (int i = 0; i < n; i++)
23 for (int j = 0; j < b[i].size(); j++) arr[index++] = b[i][j];
24 delete[] b;
25}
26
27/* Driver program to test above funtion */
28int main() {
29 float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
30 int n = sizeof(arr) / sizeof(arr[0]);
31 bucketSort(arr, n);
32
33 std::cout << "Sorted array is \n";
34 for (int i = 0; i < n; i++) std::cout << arr[i] << " ";
35 return 0;
36}
int main()
Main function.