Sort inserted Law

I. Introduction to Algorithms

Array Array [1 ... n] sorted, oh yes, the index starts, Array [0] to sentry. Each time to find the insertion position, will be larger or smaller than the current element of the ordered whole "translation" of a unit element (the element to be inserted leave room), elements can be inserted temporarily "admitted" that acts as a sentry guards.

Sentinel's role:

Before entering the lookup ① (insertion position) cycle, it saves a copy of Array [i], so as not be lost due to the shift of the recording Array [i] of the content;

② Its main role is to: Find a loop in the "monitoring" of the index variable j is out of range. Once out of range (i.e., j = 0), because Array [0]. Can compare his own, the cycle determination condition is not satisfied so find the closing cycle, thereby avoiding in the cycle each time have to detect whether j is out of range (i.e. omitted cycle determination condition "j> 0") -------------------------- saves a time unit.

note:

① In fact, all additional nodes (elements) is introduced to simplify the boundary conditions can be called sentinel.

[Example] When the first node in a single linked list is actually a sentinel

② the introduction of Sentinel that the test conditions to find the cycle time was reduced by approximately half, so for the record number of large files saving considerable time. For similar sort this very high frequency algorithms to reduce its running time as possible. The above algorithm can not be regarded as sentinels fluff, but should deeply understand and master this skill.

Two .JAVA algorithm

public class InsertSort {
    public void sort(int[] nums) {
        int temp = 0;
        for(int a=2; a< nums.length; a++) {
            nums[0] = nums[a];        
            TEMP =. 1-A ;            
             the while (the nums [TEMP] <the nums [0 ]) {// i.e. the role of sentinel herein omitted cycle determination condition temp> 0 a unit of time, thereby saving.
                nums[temp+1] = nums[temp];
                temp = temp -1;
            }
            nums[temp+1] = nums[0];
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/qcxdoit/p/11789641.html
law