Original array: a = [8,6,2,3,7,9,1]; ASC requirements.
step1: 8 because the first one, so the fixed and 8, 6 and 8 to make because of 6 less than 8, so that the exchange seat 6 and 8, the array becomes 6,8,2,3,7,9,1 . This is a relatively complete.
step2: the 2 with one of its front, i.e. more than 8, because 2 is less than 8, the seat 2 and the exchange 8, the array becomes 6,2,8,3,7,9,1.
6 to 2 and then, the exchange ratio of 2 to 6 after completing seat, 2,6,8,3,7,9,1 array becomes. Compare this round is completed.
step3: 3 with the ratio of 8, the exchange 3 with 8 seats, the array becomes 2,6,3,8,7,9,1.
The ratio of 3 and 6, the seat 3 and 6 exchange, to give 2,3,6,8,7,9,1.
The ratio of 3 to 2, because the 3 better than two hours, so the same seat, out of the loop, out of this round compared.
step4: so ......
Code
. 1 for ( int I = . 1 ; I <n-; I ++) { // the outer loop, is in fact the process is a [i] is inserted to find the right seat 2 for ( int J = I, J> 0 ; J- -) { // inner loop, as is the comparison go back, it is Save Save . 3 IF (A [I] < A [J]) . 4 the swap (A [I], A [J]); // the swap function the effect is the exchange seat . 5 the else BREAK . 6 } . 7 }
If you want the number of lines of code to write a small point, you can modify the above code,
. 1 for ( int I = . 1 ; I <n-; I ++) { // the outer loop, the whole process is in fact of a [i] to find the right insert seat 2 for ( int J = I, J> 0 && A [I ] <a [J]; J,) { // inner loop, as is the comparison go back, it is Save Save . 3 swap (a [I], a [J]); // role swap function is switched seat 4 } 5 }
As can be seen at the first code is inserted ahead of the end of the second sorting cycle layer.
The above-mentioned two codes, the use of this exchange of seats swap function, too time-consuming, so the following improvements,
. 1 for ( int I = . 1 , I <n-, I ++) { // the whole idea is to find a [i] is inserted into a suitable seat 2 int E = a [i]; . 3 int J; // J for holding element e should be inserted in the seat . 4 for (J = I, J> 0 && a [J- . 1 ]> e, J, ) { . 5 a [J] = a [J- . 1 ]; . 6 } . 7 a [J] = E; . 8 }
Thus, the idea is to improve primary and secondary 1 assignment, become a "comparison, only 1 assignment."
The swap function originally used, the use of primary swap is an exchange of views, but once the exchange is three times the assignment (high school talked about).