Java foundation - insertion sort

Direct insertion sort algorithm

(From the back to find the right position of the insert)

The basic idea: Each step will be a sort of records, the order in which the code size into the appropriate positions in the sequence already sorted (after finding the right position from back to front), until all insertion sort last.

Example:

34,4,56,17,90,65 

The first round: i = 1; temp = 4

34,34,56,17,90,65

4,34,56,17,90,65

The second round: i = 2; temp = 56

4,34,56,17,90,65

The third round: i = 3; temp = 17

4,34,  56,56,90,65

4,34,34,56,90,65

4,17,34,56,90,65

Fourth round: i = 4; temp = 90

4,17,34,56,90,65

Fifth round: i = 5; temp = 65

4,17,34,56,90,90

4,17,34,56,65,90

code show as below:

public  static  void main (String [] args) {
         int [] = {34,4,56,17,90,65 NUM };
         // comparing control rounds 
        for ( int I =. 1; I <num.length; ++ I ) {
             int TEMP = NUM [I]; // record the operand 
            int J = 0 ;
             for (= I-J. 1; J> = 0; J, ) {
                 IF (NUM [J]> = TEMP) { 
                    NUM [J + 1'd] = NUM [J]; 
                } the else {
                     BREAK ; 
                } 
                IF (NUM [+ J. 1] =!TEMP) { 
                    NUM [J + 1'd] = TEMP; 
                } 
            } 
        } 
        // output 
        for ( int X: NUM) { 
            System.out.println (X); 
        } 
        
    }

 

Guess you like

Origin www.cnblogs.com/s1023/p/11183309.html