Bubble sort
Bubble sort focuses on comparing two adjacent numbers from scratch. Each comparison bubbles the smaller number to the front and sinks the larger number to the back. After a round of sorting, the smallest must be the first, so the next sort can be one less row.
So we have j < length-1-i, so that the inner loop each time the row is completed one less sort
The following code
#include <stdio.h>
int main() {
int length = 10;
int a[length] = {3, 4, 5, 2, 1, 8, 7, 9, 6, 10};
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - 1- i; j++) {
if(a[j] > a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for (int i = 0; i < length; i++) {
printf("%d ", a[i]);
}
return 0;
}
Copy the code
Exchange method (su Xiaohong version of “C programming” called)
Instead of bubble sorting, where you’re getting smaller and smaller each time, you’re doing the same thing over and over again, so the outer loop is going from the first to the second to last, and the inner loop starts at the next number of the current I. Each time, I picks a number, and then J starts at the next digit of I and goes all the way to the last digit.
So the difference from bubble sort is that the judgment in if is the judgment of I and j, and then the scope details of the two-layer for loop.
The following code
#include <stdio.h>
int main() {
int length = 10;
int a[length] = {3, 4, 5, 2, 1, 8, 7, 9, 6, 10};
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) {
if(a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < length; i++) {
printf("%d ", a[i]);
}
return 0;
}
Copy the code
Selection method (su Xiaohong version of “C programming” called)
When you look at the exchange method, you do a lot of repetitive comparisons, which is futile, so you have the choice method.
Principle: Compare the size of two numbers each time. If the exchange conditions are met, temporarily remember the subscript of the number to be exchanged and store it in the variable K. Because smaller numbers may appear later, I just record them first and then swap them after comparing all the numbers, so that I can save many times on the swap step.
The following code
#include <stdio.h> int main() { int length = 10; int a[length] = {3, 4, 5, 2, 1, 8, 7, 9, 6, 10}; int i, j; // For (I = 0; i < length - 1; i++) { int k = i; For (j = I + 1; for (j = I + 1; j < length; j++) { if(a[k] > a[j]) { k = j; }} // If the value of k is changed, that is, it is no longer I. = i) { int temp = a[i]; A [I] = a[k]; a[I] = a[k]; a[k] = temp; } } for (int i = 0; i < length; i++) { printf("%d ", a[i]); } return 0; }Copy the code