java面试题插入排序

插入排序

//插入排序
package QFTest;
public class Test_07 {
    public static void main(String[] args) {
        int[] arrs={2,4,1,5,3,8};
        insertSortGood(arrs);
        for (int arr : arrs) {
            System.out.print(arr+"  ");
        }
    }
    public static void insertSort(int[] arrs){
        for (int i = 1; i < arrs.length; i++) {
            for (int j = i-1; j >=0 ; j--) {
                if(arrs[j]>arrs[j+1]){
                    int temp=arrs[j];
                    arrs[j]=arrs[j+1];
                    arrs[j+1]=temp;
                }
            }
        }
    }
    //优化的插入排序
    public static void insertSortGood(int[] arrs){
        for (int i = 1; i < arrs.length; i++) {
            int temp=arrs[i];
            int pos=i;
            for (int j = i-1; j >=0 ; j--) {
                if(temp<arrs[j]){
                    arrs[j+1]=arrs[j];
                    pos=j;
                }else{
                    break;
                }
            }
            arrs[pos]=temp;
        }
    }
    //优化的插入排序
    public static void insertSortGood2(int[] arrs){
        for (int i = 1; i < arrs.length; i++) {
            int temp=arrs[i];
            int pos=i-1;
            while(pos>=0&&arrs[pos]>temp){
                arrs[pos+1]=arrs[pos];
                pos--;
            }
            arrs[pos+1]=temp;

        }
    }
}
//答案
1  2  3  4  5  8  

猜你喜欢

转载自blog.csdn.net/m0_45196258/article/details/107544902