排序算法-----插入排序

//插入排序
// 假设第一位已经排序好了,从第二位开始,寻找满足条件的数,相应的数往后移
public class InsertSort {
    public static void sortInsert(int[] arr) {
        for(int i=1;i<arr.length;i++) {
            int j = i;
            int temp = arr[j];
            while(j>0&&temp<arr[j-1]) {
                arr[j]=arr[j-1];//元素后移一位
                j--;
            }
            arr[j]= temp;
        }
    }
    public static void main(String[] args) {
        int[] arr = {5,4,3,2,1};
        sortInsert(arr);
        for(int x:arr) {
            System.out.println(x);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_42061676/article/details/81093035