直接插入排序

import java.util.Arrays;

public class My {
    void insertSort(int[] arr) {
        int n=arr.length;
        for(int i=1;i<n;i++){
            int temp=arr[i];
            int j;
            for(j=i-1;j>=0;j--){  //j可能会变成-1跳出循环
                if(arr[j]>temp){
                    arr[j+1]=arr[j];
                }else{
                    break;
                }
            }
            arr[j+1]=temp;
        }
    }

    public static void main(String[] args) {
        My my = new My();
        int[] arr = {5, 6, 1, 2, 4, 7, 2, 3, 4, 6, 4};
        my.insertSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

 

posted @ 2020-08-02 22:58  执着于风  Views(119)  Comments(0)    收藏  举报