[Aha! Algorithm: algorithm 2: Bubble Sorting

Source: Internet
Author: User
The simplified bucket sorting is not only a problem left over from the previous section, but also a waste of space! For example, the range of the number of orders to be sorted is 0 ~ Between 2100000000, you need to apply for 2100000001 variables, that is, you need to write them as inta [2100000001]. Because we need to use 2100000001 "buckets" to store 0 ~ Every number of outputs between 2100000000

The simplified bucket sorting is not only a problem left over from the previous section, but also a waste of space! For example, the range of the number of orders to be sorted is 0 ~ Between 2100000000, you need to apply for 2100000001 variables, that is to say, you need to write them as int a [2100000001]. Because we need to use 2100000001 "buckets" to store 0 ~ Every number of outputs between 2100000000

The simplified bucket sorting is not only a problem left over from the previous section, but also a waste of space! For example, the range of the number of orders to be sorted is 0 ~ Between 2100000000, you need to apply for 2100000001 variables, that is to say, you need to write them as int a [2100000001]. Because we need to use 2100000001 "buckets" to store 0 ~ The number of times each number appears between 2100000000. Even if you only sort the five numbers (for example, the five numbers are 912345678, 2100000001, and), you still need "buckets", which is a waste of space! Also, what if we want to sort the number of decimal places instead of integers, such as 5.56789, 2.12, 1.1, 3.123, and 4.1234 in small and large order? Now let's learn another new sorting algorithm: Bubble sorting. It can solve these two problems very well.
The basic idea of Bubble Sorting is: compare two adjacent elements each time, and exchange them if their order is wrong.

For example, we need to sort these five numbers from large to small. Since the sorting is from big to small, that is, the smaller the back, do you think I am talking nonsense? But this sentence is very important (comment _ comment ).

First, compare the size of 1st bits and 2nd bits. Now the size of 1st bits is 12, and the size of 2nd bits is 35. It is found that 12 is smaller than 35, because the smaller we want, the lower we need to switch the positions of the two numbers. The order of the five numbers after the switch is 35 12 99 18 76.

According to the preceding method, compare the sizes of 2nd bits and 3rd bits. The values of 2nd bits and 3rd bits are 12 and 99. 12 is smaller than 99, so we need to switch the positions of these two numbers. The order of the five numbers after the switch is 35 99 12 18 76.

According to the preceding rule, compare the sizes of 3rd bits and 4th bits. If 3rd bits are smaller than 4th bits, switch the positions. The order of the five numbers after the switch is 35 99 18 12 76.

Finally, compare 4th-bit and 5th-bit. The order of the five numbers after four comparisons is 35 99 18 76 12.

After four comparisons, we found that the smallest number is already in place (the last digit. Please note that the moving process of the number 12 is amazing. Now let's recall the comparison process. Each time there are two adjacent numbers. If the number behind is greater than the previous number, the two numbers are exchanged. After the last two numbers are compared, the minimum number is in the last one. It is like a bubble, "rolling" step by step until the last bit. Therefore, this sorting method has a nice name "Bubble Sorting ".


In fact, our sorting only returns the smallest of the five numbers. Each time we return a number, we call it "one trip ". Next we will continue to repeat the previous process and normalize the remaining four.

Now, let's start the second round. The goal is to return a smaller number of 2nd characters. First, compare the 1st and 2nd bits. If the 1st bits are smaller than the 2nd bits, the switch position is used. The order of the five numbers after the switch is 99 35 18 76 12. Next, you should make a comparison of 2nd-bit and 3rd-bit, 3rd-bit, and 4th-bit. Note that at this time, you do not need to compare the 4th and 5th bits. Because after the first trip, we can determine that the 5th-bit path is the smallest. After the second round, the order of these five numbers is 99 35 76 18 12.

The "third trip" is the same. After the third round, the order of these five numbers is 99 76 35 18 12.

Now it's the last "fourth trip ". Some people asked again, isn't it already arranged? Continue? Of course, it is a coincidence that you can try another number. Can you find such a data sample? Please try it.

The principle of "Bubble Sorting" is that each trip can only return one number. That is, the first round can only determine to return the number (both 5th bits) at the last bit to the back, and the second round can only return the number (both 2nd bits) at the last 4th bits, the third round can only return the number (both 3rd bits) on the last 3rd bits, but there are still two positions in front of the number, so we still need to perform the "fourth round ".

The "fourth trip" only needs to compare the size of 1st bits and 2nd bits. Because the number at the next three locations is normalized, now the 1st bits are 99, and the 2nd bits are 76, which does not need to be exchanged. The order of these five numbers remains the same as 99 76 35 18 12. By now, the sorting has ended perfectly, and there are already four of the five numbers, so the last number can only be placed at 1st bits.

Finally, Let's sum up: if there are n numbers for sorting, we only need to normalize the n-1 number, that is, we need to perform the n-1 operation. For each "Trip", we need to compare two adjacent numbers starting from 1st bits, and put a smaller number behind them, after the comparison, move one digit backward to compare the values of the two adjacent numbers below. Repeat this step until the last number has not been reset, you do not need to compare the number of returned bits. (You can compare the number of returned bits. This is a waste of emotions ).

Is this algorithm very powerful. I remember that every time I took a group photo, I was always exchanged for it by others. At that time, I was particularly annoyed. I don't know whether the idea of the algorithm came from this. Lori said so much. The following is the code. We recommend that you first try to implement it and then see how I implement it.

# Include
 
  
Int main () {int a [100], I, j, t, n; scanf ("% d", & n); // enter n, it indicates that there are n numbers next for (I = 1; I <= n; I ++) // read n numbers into array a cyclically scanf ("% d ", & a [I]); // the core part of the Bubble Sorting for (I = 1; I <= n-1; I ++) // sorts the number of n, use only n-1 {for (j = 1; j <= n-I; j ++) // compare the number of unreturned digits until the last one starts from 1st bits, think about why n-I is enough. {If (a [j]
  

You can enter the following data for verification:

108 100 50 22 15 6 1 1000 999 0

The running result is

0 1 6 8 15 22 50 100 999 1000

By slightly modifying the code above, you can solve the problems left behind in section 1st, as shown below.

# Include
   
    
Struct student {char name [21]; char score ;}; // a struct is created here to store the name and score int main () {struct student a [100], t; int I, j, n; scanf ("% d", & n); // enter a number n for (I = 1; I <= n; I ++) // cyclically read n personal names and scores scanf ("% s % d", a [I]. name, & a [I]. score); // sort by score from high to low for (I = 1; I <= n-1; I ++) {for (j = 1; j <= n-I; j ++) {if (a [j]. score
    

You can enter the following data for verification:

5huhu 5haha 3xixi 5hengheng 2gaoshou 8

The running result is

gaoshouhuhuxixihahahengheng

The core of Bubble Sorting is a dual nested loop. The time complexity of Bubble Sorting is O (N2 ). This is a very high time complexity. Some people started to study the Bubble Sorting as early as 1956, and many people tried to improve the Bubble sorting, but the results were disappointing. For example, Knuth (Donald E. knuth, whose Chinese name is Gartner and winner of the Turing Award in 1974) said: "Bubble Sorting does not seem to be worth recommending unless it is a charming name and leads to some interesting theoretical issues." You may ask: is there any better sorting algorithm? Please wait for updates next week-fast sorting.

[Aha! Algorithm: algorithm 2: Listening to neighbors-Bubble Sorting
Http://bbs.ahalei.com/thread-4400-1-1.html (Source: Aha _ programming from here)

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.