Bucket Sort in C++

Bucket Sort:

The detailed explanation and algorithm are given here: https://rishabhjainiitbhu.blogspot.com/2019/08/sorting-algorithms.html#more

Suppose you want to sort a range of float points in the range 0 to 1.

The algorithm was:
  • Create n empty buckets (you can use vectors for it)
  • For each element arr[i] in arr. Insert arr[i] into bucket number n*arr[i]
  • sort individual buckets
  • concatenate all sorted buckets.
Here is the code that does it:

void bucketSort(float* arr, int n){
vector<float> b[n];
for (size_t i = 0; i < n; i++) {
float a = arr[i];
int index = n*a;
b[index].push_back(a);
}
for (size_t i = 0; i < n; i++) {
sort(b[i].begin(), b[i].end());
}
int index = 0;
for (size_t i = 0; i < n; i++) {
for(float t: b[i]){
arr[index++] = t;
}
}
}

No comments:

Post a Comment

Installing albert on ubuntu 19.04

Installing Albert on Ubuntu 19.04... Albert is not still released for ubuntu 19.04. But still, you can install it using the following ...