9.3.1 simplest sorting implementation
No matter which programming language you are learning, a sort algorithm is usually used as an example when you are learning loops and arrays. This algorithm is generally Bubble sorting. It is not a good name, but the simplest and easiest way to understand this algorithm. Therefore, even if everyone has already learned Bubble sorting, we will start our sorting journey from this algorithm.
Bubble sort is an exchange sort. Its basic idea is to compare the keywords of adjacent records in pairs. If the reverse order is used, it is exchanged until there is no reverse order record. The implementation of bubble can be changed in many ways in detail. We will explain the idea of Bubble Sorting in three different types of bubble implementation code. Here, let's take a look at a section that is easier to understand.
/* Exchange and sort the sequence table L (bubble sort basic edition )*/
Void bubblesort0 (sqlist * l)
{
Int I, J;
For (I = 1; I <L-> length; I ++)
{
For (j = I + 1; j <= L-> length; j ++)
{
If (L-> r [I]> L-> r [J])
{
Swap (L, I, j);/* switch the values of L-> r [I] and L-> r [J */
}
}
}
}
Strictly speaking, this code is not a standard Bubble Sorting Algorithm because it does not meet the Bubble Sorting Thought of "comparing adjacent records in two or two, it should be the simplest sort of exchange. The idea is to make every keyword compare with every keyword behind it. If it is large, it is exchanged so that the keyword at the first position will definitely become the minimum value after a loop. 9-3-2. Assume that the sequence of keywords to be sorted is {9, 1, 5, 8, 3, 7, 4, 6, 2}. When I = 1, after 9 is exchanged with 1, 1 In the first position is smaller than the keyword in the back, so it is the minimum value. When I = 2, the second position is changed from 9 to 5, 3 to 2, and the second small number is switched. The subsequent numeric transformations are similar.
It should be the easiest sorting code to write, but this easy-to-understand code is flawed. After observation, we found that sorting the positions 1 and 2 is not helpful for sorting other keywords (the number 3 is changed to the last one ). That is to say, the efficiency of this algorithm is very low.