[英]best case and worst case time complexity for insertion in unsorted array
I know this is a general question but I really do need to clear my doubt as I am studying about time complexities. 我知道这是一个普遍的问题,但是在研究时间复杂性时,我确实确实需要清除我的疑问。 I did try to look it up before posting here but found mixed answers. 在发布此处之前,我确实尝试过查找,但发现答案不一。
My question is, when inserting items in an unsorted array considering it is not full the complexity would be O(1) however if it is full it would be O(n) since we would need to copy all the items to a new array. 我的问题是,如果考虑到未排序的数组将项目插入到未排序的数组中,则复杂度为O(1),但是如果已满,则复杂度为O(n),因为我们需要将所有项目复制到新数组中。 So would we say that the best case complexity of insertion in an array is O(1) and worst case is O(n) or should we say both best and worst case are both O(n)? 因此,我们要说插入数组的最佳情况复杂度是O(1),最坏情况是O(n),还是应该说最佳和最差情况都是O(n)?
Indeed worst case insertion is O(n)
if you have to copy the whole array into a larger array. 实际上,如果必须将整个数组复制到更大的数组中,最坏的情况是插入O(n)
。 But you must remember, it is the amortize cost we care about. 但是您必须记住,这是我们关心的摊销成本。
Think about it this way: how often do I have to copy the whole array ? 这样考虑:我必须多久复制一次整个数组? Once in n
times. n
次。 So for n-1
I will pay O(1)
and for the final insertion O(n)
. 因此,对于n-1
我将支付O(1)
,最后一次插入O(n)
。 In total ~2n
for n
insertions. 对于n
插入,总计~2n
。 Average O(1)
per op. 每个操作的平均O(1)
。 Maybe it is easier for you to think about it as O(2)
. 也许您更容易将其视为O(2)
。
Now to maintain that, each time the array is filled, twice that size must allocated, so for each item you insert, you pay extra 1 for the time you might need to copy the corresponding item in the first half of the array. 现在要保持这一点,每次填充数组时,都必须分配两倍的大小,因此对于插入的每个项目,您可能需要为复制数组前半部分中的相应项目支付额外的1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.