插入排序

插入排序的意思是,在一组有序的数中,找到待插入数合适的位置,然后将数放入

如下图 原数组9,3,4,2,6,7,5,1,我们假设为4,5,9为排好序的,2,6,7,8,1位带插入的数,i j指向数组中的2,操作如下图所示

代码如下

 public static void insertSort(int[] arr){
        int temp=0;
        int i=0;
        int j=0;
        for( i=1;i<arr.length;i++){//下标从1开始假定第一个数是有序的
            j=i;
            temp=arr[i];
            while(j>0 && temp<arr[j-1]){
                arr[j]=arr[j-1];
                j--;
            }
            arr[j]=temp;
            
        }
        
    } 

原文地址:https://www.cnblogs.com/wanglingdeboke/p/9481923.html