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