直接插入排序

package com.insert;

import java.util.Arrays;

/**
 * 直接插入排序
 * @author wanjn
 *
 */
public class InsertSort {
    public static void main(String[] args) {
        int[] a = {50,3,6,1,7,9,6};
        System.out.println(Arrays.toString( insertSort(a)));;
    }
    private  static int[] insertSort(int[] a){
        int temp;
        int j ;
        //a[0] 本身就是有序的,所以从1到n-1插入数据
        for (int i = 1; i < a.length; i++) {
            //将 待插入数据 保存下来,方便比较以及 有序段数据的移动
            temp = a[i];
            //然后依次往有序段前面查找 即从i-1到0之间的有序段中查找到待插入数据中数据的插入位置
            //假如是从小到大,只有当待插入数据 temp < a[j] 的时候才需要将a[j]的数据往后移动,否则就找到了插入位置,直接插入即可
            for ( j = i-1;j>=0&& temp <a[j]; j--) {
                //将大的往后挪
                 a[j+1] =  a[j]; 
            }
            //当temp >=a[j]时,则插入
            //不满足条件时,j已经--了,需要加1加回来
            a[j+1]=temp;
        }
        return a;
    }
}
原文地址:https://www.cnblogs.com/wanjn/p/8551954.html