插入排序:直接插入排序

1.插入排序—直接插入排序(Straight Insertion Sort)

排序方法 時間複雜度 空間複雜度 穩定性 複雜性
平均情況 最壞情況 最好情況
插入排序 O(n2) O(n2) O(n) O(n) 穩定 簡單
private void insertSort(int[] array) {
        int arraySize = array.length;

        for (int i = 1; i < arraySize; i++) {
            int j = i;

            int waitInsert = array[i];//存儲當前待插入值
            while(j > 0 && waitInsert < array[j - 1]) {//在待插入值向前循環比較
                array[j] = array[j - 1];//遇到比自身大的,將該大值向後移一位,
                j--;
            }
            array[j] = waitInsert;//比自身小,鎖定當前索引插入待插入值
        }
        System.out.println(Arrays.toString(array));
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章