景兄弟手撕算法之插入排序

插入排序的基本思想是将一个记录插入到已经排好序的有序表中,从而一个新的、记录数增1的有序表

升序的插入排序:

package test1;

import java.util.Arrays;

public class InsertSort {
    public static void main(String[] args) {
        int[] arr = new int[]{2,1,5,3,4};

        for(int i=0;i<arr.length;i++){
            int current = arr[i];//取出当前要和已排序序列比较的元素

            int preIndex = i-1;//在有序区间往前扫描指针

            while (preIndex >=0 && arr[preIndex]>current){
                arr[preIndex+1]=arr[preIndex];
                preIndex--;
            }
            arr[preIndex+1] = current;
            System.out.println(Arrays.toString(arr));
        }
    }
}

输出结果:

[2, 1, 5, 3, 4]
[1, 2, 5, 3, 4]
[1, 2, 5, 3, 4]
[1, 2, 3, 5, 4]
[1, 2, 3, 4, 5]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章