首页 > 技术文章 > 插入排序

wliamchen 2020-07-02 18:56 原文

从左开始遍历,找到比当前值小的后一个索引位置,然后插入

    public void insertSort(int[] num){
        for (int i = 1; i < num.length; i++) {
            int preIndex = i - 1;
            int currentVal = num[i];
            while(preIndex >= 0 && num[preIndex] > currentVal){
                num[preIndex+1] = num[preIndex];
                preIndex--;
            }
            num[preIndex+1] = currentVal;
        }
    }

推荐阅读