Two common C language sorting algorithms:
1.
10 integers must be input, sorted from large to small.
Input: 2 0 3-4 8 9 5 1 7 6
Output: 9 8 7 6 5 3 2 1 0-4
Solution: Select sorting
The implementation code is as follows:
# Include <stdio. h>
Int main (int argc, const char * argv []) {
Int num [10], I, j, k, l, temp;
// Use an array to save input data
For (I = 0; I <= 9; I ++)
{
Scanf ("% d", & num [I]);
}
// Use two for nested loops for data size comparison and sorting
For (j = 0; j <9; j ++)
{
For (k = j + 1; k <= 9; k ++)
{
If (num [j] <num [k]) // num [j] <num [k]
{
Temp = num [j];
Num [j] = num [k];
Num [k] = temp;
}
}
}
// Use a for loop to output sorted data in the array
For (l = 0; l <= 9; l ++)
{
Printf ("% d", num [l]);
}
Return 0;
}
2.
10 integers must be input, sorted from large to small.
Input: 2 0 3-4 8 9 5 1 7 6
Output: 9 8 7 6 5 3 2 1 0-4
Solution: Bubble Sorting
The implementation code is as follows:
# Include <stdio. h>
Int main (int argc, const char * argv []) {
// Use an array to store data
Int num [10], I, j, k, l, temp;
// Use for to read data one by one
For (I = 0; I <= 9; I ++)
{
Scanf ("% d", & num [I]);
}
// Use two for loops to compare and bubble data
For (j = 0; j <9; j ++)
{
For (k = 0; k <9-j; k ++)
{
If (num [k] <num [k + 1]) // num [k] <num [k + 1]
{
Temp = num [k];
Num [k] = num [k + 1];
Num [k + 1] = temp;
}
}
}
// Use a for loop to output sorted data in the array
For (l = 0; l <= 9; l ++)
{
Printf ("% d", num [l]);
}
Return 0;
}