Sorting (1) Simple exchange sorting

Source: Internet
Author: User

Sort (1) Simple exchange sort by Drizzle QQ: 253786989
2012-02-01

Sample Code:

// Simple exchange sorting int data [9] = {8, 2, 1, 4, 9, 5, 7, 3, 6}; For (INT I = 0; I <9; ++ I) {for (Int J = I + 1; j <9; ++ J) {If (data [I]> data [J]) {int temp = data [I]; data [I] = data [J]; data [J] = temp ;}}}

Thoughts:

The code above is used as an example. First, compare the numbers at the second position with the numbers at the second position. If the numbers are greater than them, data is exchanged. After such a loop, the number at the first position must be the smallest of the nine data, that is, 1.

The first is the comparison between 8 and 2, where 8 is greater than 2. After the exchange, the data sequence is: 2, 8, 1, 4, 9, 5, 7, 3, 6. Compared with 1, 2 is greater than 1. After exchange, the data sequence is 1, 8, 2, 4, 9, 5, 7, 3, 6. Then compare 1 with 4, and 1 is smaller than 4 without data exchange. Similarly, compare data 1 at the first position with other data, and compare data 6 at the last position. After such a loop, the data sequence is: 1, 8, 2, 4, 9, 5, 7, 3, 6. The data at the fifth position is the smallest of the nine data records.

Then, compare the number at the third position with the number at the third position in sequence. The first is 8 to 2, and the data sequence after the exchange is: 1, 2, 8, 4, 9, 5, 7, 3, 6. Then 2 is compared with 8, 4, 9, 5, 7, 3, 6 in sequence, and no data is exchanged. After such a round of exchange, the data sequence is: 1, 2, 8, 4, 9, 5, 7, 3, 6. After the two rounds of data exchange, the data at the first two locations is already in order.

Then compare the number at the fourth position with the number at the fourth position in sequence.

And so on.

The best way to understand the sorting program algorithm is to debug the program and monitor the change process of the data sequence in the data array:

Time Complexity:

O (n2)

Sort (1) Simple exchange sort by Drizzle QQ: 253786989
2012-02-01

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.