Created
January 19, 2019 01:33
-
-
Save benapie/3df28b56946ae6a550805acca6f1db34 to your computer and use it in GitHub Desktop.
Bucket sort implementation in C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void bucket_sort(int data_array[], int array_size) { | |
// First we find the maximum value in the list so we know how much space to allocate. | |
int maximum_value = 0; | |
for (int i = 0; i < array_size; ++i) { | |
if (data_array[i] > maximum_value) { | |
maximum_value = data_array[i]; | |
} | |
} | |
auto bucket_vector = std::vector<unsigned >(static_cast<unsigned int>(maximum_value + 1)); | |
// And now we fill our buckets. | |
for (int i = 0; i < array_size; ++i) { | |
bucket_vector[data_array[i]]++; | |
} | |
// Now we convert back to our array. | |
int count = 0; | |
for (int i = 0; i < bucket_vector.capacity(); ++i) { | |
for (int j = 0; j < bucket_vector[i]; ++j) { | |
data_array[count] = i; | |
count++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment