Remember before in the University of Learning C language, at the beginning is very laborious.
One of the entry-level algorithms is called bubble sort, which is also known as the bubbles sort method. It was very interesting to have a contact with it at that time, because it was fun. OK, no more nonsense, let's go over this bubble sort together briefly.
A. Printing rows and columns is typically a simple code that outputs 4 rows of 4 columns *:
for (int i = 1,i < 5,i++) {for
(int j = 1,j < 5,j++) {
printf ("*");
}
printf ("n\");
}
Two. Print "Upper triangle":
for (int i = 1,i < 5,i++) {for
(int j = 1,j < i,j++) {
printf ("*");
}
printf ("n\");
}
Three. Print "Bottom triangle":
for (int i = 1,i < 5,i++) {for
(int j = I,j < 5,j++) {
printf ("*");
}
printf ("n\");
}
Four. Reader, the key place will come. Bubble sort is actually a "bottom triangle" printing principle, because in an array of sorting each time from the first element start and the following elements than a round, determine a maximum value, "sink" to the last one, each round will be less than a number of comparisons, So the bubble sort principle is used to print the "down triangle Principle":
for (int i = 0; i < 4; i++) {for
(int j = i; J < 4; J +) {
if (Nums[j] < nums[j+1]) {
int temp = num S[J];
NUMS[J] = nums[j+1];
NUMS[J+1] = temp;
}}}
Careful friends should find that this sort of an array of results will not be expected results, but I obviously use the "Print the next triangle" Ah! Remember at that time the teacher gave us such a job, let everyone back to think, tip with the "bottom triangle" principle of printing, then feel good pit dad Ah! (So the impression of this bubble sort is quite impressive now)
Five. Yes, there are some small details, I was thinking for a while, and then finally found the problem, because the next round of every comparison from the first number to start with the number of the following comparison, if you change the initialization value, The first number can only be compared with the 2nd number once and will not participate in the next round of comparisons. So we should put this in a different form.
for (int i = 0; i < 4; i++) {for
(int j = 0; J < 4-i; J +) {
if (NUMS[J) < nums[j+1]) {
int temp = Nums[j];
NUMS[J] = nums[j+1];
NUMS[J+1] = temp;
}}}
Six. Haha, the principle is good, change a form after the output is no problem.
Seven. Add that you typically replace 4 with a variable, such as length, or you can use a macro-defined method to define a better definition of a macro. When you use length, there is a benefit to the length-1, which is to prevent cross-border problems, And the last remaining one is not going to be compared when the size is sorted. So length-1 is no problem.