插入排序(InsertSort)

算法思路:

假定这个数组的序是排好的,然后从头往后,如果有数比当前外层元素的值大,则将这个数的位置往后挪,直到当前外层元素的值大于或等于它前面的位置为止.这具算法在排完前k个数之后,可以保证a[1…k]是局部有序的,保证了插入过程的正确性


public class InsertSort {
    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] a = new int[] {5, 2, 4, 6, 1, 3};
          
        for(int i = 1; i < a.length; i ++) { //外层元素从第二个开始
            int key = a[i];
              
            int j = i - 1;
              
            while(j >= 0 && a[j] > key) {
                a[j + 1] = a[j]; //已经排好序的子序列元素后移
                j --;
            }
            a[j + 1] = key;
        }
          
        for(int i = 0; i<a.length; i++) {
            System.out.print(a[i]);
            System.out.print(" ");
        }
    }
}

点赞