Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to achieve bucket sorting in C++

Shulou Source: shulou.com Published: 2022-05-31 13:53:33 09月10日 Update

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

Tags: Sort array minimum loop generation statistics Cumulative maximum sequence maximum output complexity complexity time result content interval principle reality situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Docker vpn Huawei NVidia