"Ah ha! Algorithm "Fastest and simplest sort--bucket sort

Source: Internet
Author: User

Transferred from: http://bbs.ahalei.com/thread-4399-1-1.html

Fastest and simplest sort--bucket sort

in the world in which we live we are all sorted. Queued will be in accordance with the height of the ranking, the exam should be ranked according to the score, online shopping will be sorted according to Price, e-mail messages in chronological order ... In short, a lot of things need to sort, can say the sort is everywhere. Now let's take a concrete example to introduce the sorting algorithm.

The first appearance of our protagonist Xiao Hum, above this lovely baby is. After the final exams, the teacher will rank the students according to their grades from high to low. Xiao hum of the class only 5 students, the 5 students were tested 5 points, 3 points, 5 points, 2 points and 8 points, ah test is really miserable (out of 10 points). Next, the scores are sorted from large to small, which is 8 5 5 3 2. Do you have any good way to write a program that allows the computer to randomly read 5 numbers and then turn these 5 numbers from large to small output? Think about it for at least 15 minutes before you look down (*^__^*).

We can solve this problem by simply using a one-dimensional array. Make sure you really think about it and look down.

First we need to apply for an array of size 11 int a[11]. OK now you have 11 variables, numbered from a[0]~a[10]. At first, we initialized the a[0]~a[10] to 0, indicating that none of the scores were ever. For example A[0] is equal to 0 means that no one has been 0 points, the same a[1] equals 0 means that no one has been 1 points ... a[10] equals 0 means that no one has ever had 10 points at the moment.

next start to deal with each person's score, the first person's score is 5 points, we will be relative a[5] value in the original base increased 1, the value of a[5] from 0 to 1, indicating that 5 points appeared once.

the second person's score is 3 points, we put the relative a[3] value on the original basis of 1 increase, the value of a[3] from 0 to 1, indicating that 3 points have occurred once.

Watch out! The third person's score is also "5 points", so the value of a[5] needs to be increased by 1 on this basis, and the value of a[5] will be changed from 1 to 2. Indicates that 5 points have occurred two times.

The scores of the fourth and fifth persons are dealt with in the way just now. The final result is the figure below.

you find no, the number in a[0]~a[10] is actually 0 points to 10 points each score appears. Next, we just need to print out the points that have occurred and print them several times, as follows. A[0] is 0, which means "0" has not appeared, does not print. A[1] is 0, which means "1" has not appeared, does not print. A[2] is 1, which means "2" appears 1 times, printing 2. A[3] is 1, which means "3" appears 1 times, printing 3. A[4] is 0, which means "4" has not appeared, does not print. A[5] is 2, which means "5" appears 2 times, printing 5 5. A[6] is 0, which means "6" has not appeared, does not print. A[7] is 0, which means "7" has not appeared, does not print. A[8] is 1, which means "8" appears 1 times, printing 8. A[9] is 0, which means "9" has not appeared, does not print. A[10] is 0, which means "10" has not appeared, does not print. The final screen output "2 3 5 5 8", the complete code is as follows.
1234567891011121314151617181920 #include <stdio.h>int main(){    int a[11],i,j,t;    for(i=0;i<=10;i++)        a[i]=0;  //初始化为0                    for(i=1;i<=5;i++)  //循环读入5个数    {        scanf("%d",&t);  //把每一个数读到变量t中        a[t]++;  //进行计数    }    for(i=0;i<=10;i++)  //依次判断a[0]~a[10]        for(j=1;j<=a[i];j++)  //出现了几次就打印几次            printf("%d ",i);    getchar();getchar();    //这里的getchar();用来暂停程序,以便查看程序输出的内容    //也可以用system("pause");等来代替    return 0;}
Enter data as

Careful observation of the students will find that just realized is from small to large sort. But what should we do if we ask for a sort from the big to the small? Or first think about it and then look down oh.

It's actually very simple. Just change for (i=0;i<=10;i++) to for (i=10;i>=0;i--) OK, go ahead and try it.

This sort of method we call him "bucket sort" for the moment. Because in fact the real bucket sort is more complicated than this, discussed in detail later, the algorithm has been able to meet our needs.

This algorithm is like having 11 barrels, numbered from 0~10. Each occurrence of a number, will be the corresponding number of the bucket in a small flag, and finally as long as the number of a few small flags in each bucket OK. For example, there are 1 small flags in the 2nd barrel, indicating that 2 appeared once, 3rd had 1 small flags, 3 had appeared once, 5th were in the barrels, 2 had been seen, 5 had been in the bucket, there were two small flags, 8th had appeared.

Now you can try to enter an integer between n 0~1000 and sort them from large to small. To remind you that if you need to sort an integer that ranges between 0~1000, we need 1001 buckets to represent the number of occurrences of each of the 0~1000 between the two. In addition, the role of each bucket here is actually "mark" each number of occurrences, so I like to change the previous array A to a more appropriate name book (the book this word has a record, the meaning of the mark), the code is implemented as follows.
123456789101112131415161718 #include <stdio.h>int main(){    int book[1001],i,j,t,n;    for(i=0;i<=1000;i++)        book[i]=0;    scanf("%d",&n);//输入一个数n,表示接下来有n个数    for(i=1;i<=n;i++)//循环读入n个数,并进行桶排序    {        scanf("%d",&t);  //把每一个数读到变量t中        book[t]++;  //进行计数,对编号为t的桶放一个小旗子    }    for(i=1000;i>=0;i--)  //依次判断编号1000~0的桶        for(j=1;j<=book[i];j++)  //出现了几次就将桶的编号打印几次             printf("%d ",i);    getchar();getchar();    return 0;}
You can enter the following data to verify
108 100 50 22 15 6 1 1000 999 0
The running result is
1000 999 100 50 22 15 8 6 1 0

Finally, the question of time complexity. The loop of line 6th in the code has a total cycle of M (M is the number of buckets), the code for line 9th Loops n times (n is the number of rows to be sorted), and the 14th and 15 lines are m+n times. Therefore the entire sort algorithm carried out altogether m+n+m+n times. We use the capital letter O to represent the time complexity, so the time complexity of the algorithm is O (m+n+m+n) i.e. O (m+n). We can ignore the smaller constants when we talk about time complexity, and the time complexity of the final bucket sequencing is O (m+n). Also, in the case of time complexity, N and M are usually in uppercase letters O (m+n).

This is a very fast sorting algorithm. Barrel sequencing has been used since the 1956, and the basic idea of the algorithm is proposed by E.j.issac R.c.singleton. Previously said, this is not really a bucket sorting algorithm, the real bucket sorting algorithm is more complex than this. But considering here is the first of the algorithm explained, I think the more simple and easy to understand the better, the real bucket sort of stay in the future to talk about it. One thing to note is that the simplified bucket sorting algorithm We are currently learning is not really a sort algorithm in the real sense. Why is it? For example, there is no point in encountering the following example.

Now there are 5 individual names and scores: Huhu 5, haha 3, Xixi 5, Hengheng 2 and Gaoshou 8. Please follow the scores from high to low and output their names. That should output Gaoshou, Huhu, Xixi, haha, Hengheng. Did you find the problem? If you use the bucket sorting algorithm that we just simplified, just sort the fractions. The final output is just fractions, but no sort of person. In other words, we do not now know which one the ranked score originally corresponds to! What should we do about it? Don't worry, listen to the next-bubble sort.

code word is not easy ah, reprint please indicate the source ^_^"One Week Algorithm" algorithm 1: Fastest and simplest sort--bucket sortHttp://bbs.ahalei.com/thread-4399-1-1.html

"Ah ha! Algorithm "Fastest and simplest sort--bucket sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.