Two common C language sorting algorithms:

Source: Internet
Author: User

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;

}

Related Article

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.