How to achieve bucket sorting in C++
This article mainly explains "C++ how to achieve bucket sorting", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to implement bucket sorting in C++"!
principle
Principle Description: According to the actual situation of the array to be sorted, generate a one-dimensional array of a certain length, used to count the number of repetitions of different values of the array to be sorted, and then repeat the output in sequence after completing the statistics.
Implementation steps:
Determine the maximum and minimum values of the array to sort
Generate bucket array and initialize
statistic that array to be sorted, and put the statistical results into the corresponding bucket
Loop the output bucket and replace the original sequence
void getRand(int arr[], int len, int min, int max) { std::default_random_engine e; e.seed(time(0)); std::uniform_int_distribution u(min,max); for (int i = 0; i
< len; i++) arr[i] = u(e);}桶排序实现#include void bucketSort(int arr[], int len) { // 确定最大值和最小值 int max = INT_MIN; int min = INT_MAX; for (int i = 0; i < len; i++) { if (arr[i] >max) max = arr[i]; if (arr[i] < min) min = arr[i]; } //Generate bucket array //Set the minimum value to index 0 and interval between buckets to 1 int bucketLen = max - min + 1; //Initialize bucket int bucket[bucketLen]; for (int i = 0; i < bucketLen; i++) bucket[i] = 0; //put it in the bucket int index = 0; for (int i = 0; i < len; i++) { index = arr[i] - min; bucket[index] += 1; } //replace original sequence int start = 0; for (int i = 0; i < bucketLen; i++) { for (int j = start; j < start + bucket[i]; j++) { arr[j] = min + i; } start += bucket[i]; #include #include #include //const int MAX = 30;const int LEN = 64; void bucketSort(int arr[], int len);void getRand(int arr[], int len, int min, int max); int main() { int arr[LEN] = {0}; //generate random values getRand(arr,LEN,0,MAX); //Print random values std::cout