簡體   English   中英

此插入排序的時間復雜度 function

[英]Time complexity for this insertion sort function

function insertion(arr_instance) {
let arr = arr_instance;

for (i=1; i<arr.length; i++) {

    // Get the current element first.
    let currentElement = arr[i];

    // Spit the left side of the array.
    let leftPortion = arr.slice(0, i);
    let indexToInsert = null;

    // Iterate throught the array from the right to the left, while checking if the next
    // element is lesser than any of the elements in the split array. If it is, then insert.

    for(j=leftPortion.length-1; j>=0; j--) {
        if(currentElement < leftPortion[j]) {
            indexToInsert = j;
        } else {
            indexToInsert = j+1;
            break;
        }
    }

    // Insert in the correct index.
    leftPortion.splice(indexToInsert, 0, currentElement);
    arr.splice(0, i+1);
    arr = leftPortion.concat(arr);

    // Repeat the same for the next element in the unsplit array.

}

return arr;
}

這是我對插入排序的實現。 如果我是對的,這應該具有O(n^2)的時間復雜度,對嗎? 我有疑問,因為我在外循環中使用了splice() function ,據說它具有線性時間復雜度O(n) 但由於它不在內部for循環內,它應該相對於內部for循環以線性時間運行,對嗎? 我只需要對我的思維過程進行一些驗證。

插入 function 的復雜度為 O(n^2)。 復雜度的解釋如下。 我們舉一個數組長度為 5 的例子。

外部循環 (i) 從 1 運行到數組的長度 - 在我們的例子中是 1 到 5。 現在,內循環 (j) - 從左子數組的長度向下運行到 0。這個長度在外循環的每次迭代中都會發生變化。

leftPortion = arr.slice(0, i)

根據上面的說法,在第一次迭代中,當 i = 1 時,左子數組的長度將為 1。類似地,對於連續迭代,分別為 2、3、4、5。 所以,

當 i = 1 時,j 從 1 到 0 執行,所以,1 次

當 i = 2 時,j 從 2 到 0 執行,所以,2 次

當 i = 3 時,j 從 3 到 0 執行,所以,3 次

當 i = 4 時,j 從 4 到 0 執行,所以,4 次

當 i = 5 時,j 從 5 到 0 執行 5 次

所以當數組大小為 5 時,執行的總步數 = 1 + 2 + 3 + 4 + 5 = 15

當數組大小為 n 時,總步數 = n(n+1)/2 = O(n^2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM