Java中的插入排序和希爾排序

1.插入排序

在這裏插入圖片描述

    //升序爲例
    public static void insertSort(int[] array) {
        for (int bound = 1;bound<array.length;bound++) {
            int tmp = array[bound];
            int cur = bound-1;
            for (;cur>=0;cur--) {
                if (array[cur]>tmp) {
                    array[cur+1] = array[cur];

                }else {
                    break;
                }
            }
            array[cur+1] = tmp;
        }
    }
    //特性1:如果數組已經比較小了,使用插入排序效率非常高
    //特性2:如果數組本身已經接近有序,此時插入排序效率也很高

從bound位置開始往前找,如果比當前位置的值大,就往後移,一直找到比那個值小的,然後把他放到這個數的後面。

2.希爾排序

在這裏插入圖片描述

public static void shellSort(int[] array) {
        int gap = (array.length)/2;
        while (gap>1) {
            insertSortGap(array,gap);
            gap = gap/2;
        }
        insertSortGap(array,1);
}

public static void insertSortGap(int[] array,int gap) {
        for (int bound = gap;bound<array.length;bound++) {
            int tmp = array[bound];
            int cur = bound-gap;
            for (;cur>=0;cur-=gap) {
                if (array[cur]>tmp) {
                    array[cur+gap] = array[cur];
                }else {
                    break;
                }

            }
            array[cur+gap] = tmp;

        }
}

建議gap取size/2,size/4,size/8…比較好
這個代碼與插排的比較類似,只要注意同一組相鄰兩個元素之間下標相差gap就好了。

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