Data Architecture and Algorithm-Graphical Bucket Sort Algorithm and C/C++ Code Implementation [Recommended Collection]

1. Introduction to Bucket Sorting

The principle of Bucket Sort is very simple. It divides numbers into a limited number of buckets.

Suppose there are N integers in the array a to be sorted, and the range of the data in the array a is known [0, MAX). When sorting buckets, a bucket array r with a capacity of MAX is created, and all elements of the bucket array are initialized to 0; each unit in the bucket array with a capacity of MAX is regarded as a "bucket".
When sorting, traverse the array a one by one, and use the value of the array a as the subscript of the "bucket array r". When the data in a is read, the value of the bucket is increased by 1. For example, if the array a[3]=5 is read, the value of r[5] is +1.

Two, bucket sorting graphic description

Bucket sort code

/*
 * 桶排序
 *
 * 参数说明:
 *     a -- 待排序数组
 *     n -- 数组a的长度
 *     max -- 数组a中最大值的范围
 */
void bucketSort(int a[], int n, int max)
{
    
    
    int i,j;
    int buckets[max];

    // 将buckets中的所有数据都初始化为0。
    memset(buckets, 0, max*sizeof(int));

    // 1. 计数
    for(i = 0; i < n; i++) 
        buckets[a[i]]++; 

    // 2. 排序
    for (i = 0, j = 0; i < max; i++) 
    {
    
    
        while( (buckets[i]--) >0 )
            a[j++] = i;
    }
}

bucketSort(a, n, max) is used to sort the array a, n is the length of the array a, and max is the range [0,max) to which the largest element in the array belongs.

Suppose a={8,2,3,4,3,6,6,3,9}, max=10. At this time, put all the data of the array a into the bucket that needs to be 0-9. As shown below:

Insert picture description here
After putting the data in the bucket, through a certain algorithm, the data in the bucket is extracted and converted into an ordered array. We get the result we want.

The editor recommends my own linuxC/C++ language technology exchange group: [ 1106675687 ] I have compiled some learning books and video materials that I think are better to share in the group files, and you can add them if you need them!
Insert picture description here

Three, bucket sorting implementation

Bucket sort C implementation
Implementation code (bucket_sort.c)

 View Code

Bucket sorting C++
implementation code (BucketSort.cpp)

View Code

Bucket Sorting Java Implementation
Implementation Code (BucketSort.java)

View Code

The principles and output results of the above three implementations are the same. Here is their output:

before sort:8 2 3 4 3 6 6 3 9 
after  sort:2 3 3 3 4 6 6 8 9 

Guess you like

Origin blog.csdn.net/m0_50662680/article/details/113055922