Simple sorting algorithm - "bucket sort" (simple version)

"Aha! Algorithm "notes

Bucket sort the name suggests, like a bucket with a sequential same thing to hold things sorted.
  Then give you an example:
  I now have five points 3,1,2,4,3 (out of 5) five fractional need in ascending order 12334 to a row, we use the bucket sort the rows of how it?


  code show as below:

#include<stdio.h>
int main()
 {
     int buc[6]={0};        //定义木桶并初始化,因为我们要在012345个分数中排序所以要定义6个桶。
     int i,j,t,n;           
     scanf("%d",&n);        //输入一个数n+1,表示接下来有n个数要排序
     for(i=1;i<n;i++)       //循环读入n个数,并进行排序
     {
         scanf("%d",&t);    //把每一个数读到变量t中;
         buc[t]++;          //进行计数;
     }
     for(i=0;i<=5;i++)      //判断0到5的桶
         for(j=1;j<=buc[i];j++)//出现了几次就将桶的编号打印几次;
            printf("%d",i);

}

In the seventh row in this cycle we will each score into the corresponding bucket.

In the twelfth row and Thirteen cycle where we will print out the score, just like the title as 31243, with two 3 in the seventh row after buc [t] ++, for the first time to buc [3] + + once, the last time an entry is 3, so buc [3] continue to add 1, so buc [3] accumulate twice.

3 is put into a corresponding fraction III bucket, bucket and finally look III has several scores 3, in order cycle of the output.

The complexity of the problem of time, the seventh row cycle M times, the M + N cycle times in the twelfth and thirteenth row, so the entire ranking algorithm executed a total of M + N + M + N times.

We uppercase letter O time complexity, so the time complexity of this algorithm is O (2 * (M + N), we say that when the time complexity is negligible small constant, and ultimately is O (M + N).

Let me say to their own understanding, I think that when the number of items you want to sort the array and the contents are similar can use this sort, with a fixed array of items and the number of records in order to sort the output, not so complicated.

This ordering is not regarded as bucket sort in the true sense, a real bucket sort algorithm is more complicated than this.

This is my first time writing blog, just read the book, own summary again, the code was borrowed and made some changes on the book.

If there is any misunderstanding or wrong, please correct me big brother.

Guess you like

Origin blog.csdn.net/qq_36156580/article/details/91415941