简体   繁体   English

在未排序数组中插入的最佳情况和最坏情况时间复杂度

[英]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.

相关问题 最佳情况时间复杂度检查数组是否未排序 - Best case time Complexity to check if the array is unsorted 为什么对未排序数组O(n)进行线性搜索的最佳和最差情况? - Why is the best and worst case of linear search of an unsorted array O(n)? 最坏情况下的时间复杂度列表 - Worst case time complexity lists 查找阵列中最小元素索引的时间复杂度分析 - 最差,平均和最佳情况 - Time complexity analysis in finding index of smallest element in an array-worst,average and best case 在一个密切排序的元素数组中搜索元素的最坏情况时间复杂度? - Worst case time complexity to search an element in a closely sorted array of elements? 此算法在最坏情况下的时间复杂度是多少? - What would be the worst case time complexity for this algorithm? 在插入、删除的最佳情况下,排序数组、排序链表和二叉搜索树的时间复杂度是多少 - What's the time complexity for Sorted Array, Sorted Linked List and Binary Search Tree in Best Case for Insertion, Deletion 近排序数组的插入排序最坏时间复杂度? - insertion sort worst time complexity for near sorted array? 为什么这个算法的最坏情况时间复杂度是 O(n)? - why is the worst case time complexity of this algorithm O(n)? 比较中最差和最好的情况 - Worst and best case in making comparisons
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM