Kautilya Kondragunta
Kautilya Kondragunta

Reputation: 155

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;
}

This is my implementation of the insertion sort. And if I'm right this should have a time complexity of O(n^2) right? I have a doubt because I'm using a splice() function within the outer loop and it is said to have a linear time complexity O(n). But since it's not within the inner for loop, it should run in linear time with respect to the inner for loop correct?. I Just needed some validation on my thought process.

Upvotes: 0

Views: 558

Answers (1)

Suyash Krishna
Suyash Krishna

Reputation: 241

The complexity of the insertion function is O(n^2). The explanation of the complexity is as follows. Let's take an example where the array length is 5.

The outer loop (i) runs from 1 to length of array - 1 to 5 in our case. Now, the inner loop (j) - runs from length of left subarray down to 0. This length changes in every iteration of the outer loop.

leftPortion = arr.slice(0, i)

As per the above statement, in the first iteration when i = 1, the length of left subarray would be 1. Similarly for successive iterations, it would be 2,3,4,5 respectively. So,

When i = 1, j executes from 1 to 0 so, 1 time

When i = 2, j executes from 2 to 0 so, 2 times

When i = 3, j executes from 3 to 0 so, 3 times

When i = 4, j executes from 4 to 0 so, 4 times

When i = 5, j executes from 5 to 0 so, 5 times

So when array size is 5, total number of steps executed = 1 + 2 + 3 + 4 + 5 = 15

When array size is n, total steps = n(n+1)/2 = O(n^2)

Upvotes: 0

Related Questions