[英]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?如果我是对的,这应该具有
O(n^2)
的时间复杂度,对吗? 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)
.我有疑问,因为我在外循环中使用了
splice()
function ,据说它具有线性时间复杂度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?.但由于它不在内部
for
循环内,它应该相对于内部for
循环以线性时间运行,对吗? I Just needed some validation on my thought process.我只需要对我的思维过程进行一些验证。
The complexity of the insertion function is O(n^2).插入 function 的复杂度为 O(n^2)。 The explanation of the complexity is as follows.
复杂度的解释如下。 Let's take an example where the array length is 5.
我们举一个数组长度为 5 的例子。
The outer loop (i) runs from 1 to length of array - 1 to 5 in our case.外部循环 (i) 从 1 运行到数组的长度 - 在我们的例子中是 1 到 5。 Now, the inner loop (j) - runs from length of left subarray down to 0. This length changes in every iteration of the outer loop.
现在,内循环 (j) - 从左子数组的长度向下运行到 0。这个长度在外循环的每次迭代中都会发生变化。
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.根据上面的说法,在第一次迭代中,当 i = 1 时,左子数组的长度将为 1。类似地,对于连续迭代,分别为 2、3、4、5。 So,
所以,
When i = 1, j executes from 1 to 0 so, 1 time当 i = 1 时,j 从 1 到 0 执行,所以,1 次
When i = 2, j executes from 2 to 0 so, 2 times当 i = 2 时,j 从 2 到 0 执行,所以,2 次
When i = 3, j executes from 3 to 0 so, 3 times当 i = 3 时,j 从 3 到 0 执行,所以,3 次
When i = 4, j executes from 4 to 0 so, 4 times当 i = 4 时,j 从 4 到 0 执行,所以,4 次
When i = 5, j executes from 5 to 0 so, 5 times当 i = 5 时,j 从 5 到 0 执行 5 次
So when array size is 5, total number of steps executed = 1 + 2 + 3 + 4 + 5 = 15所以当数组大小为 5 时,执行的总步数 = 1 + 2 + 3 + 4 + 5 = 15
When array size is n, total steps = n(n+1)/2 = O(n^2)当数组大小为 n 时,总步数 = n(n+1)/2 = O(n^2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.