More appropriate to say Amortized O(1) vs O(n) for insertion into unsorted dynamic array?

余生颓废 提交于 2019-12-12 15:09:19

问题


This falls under "a software algorithm" from stackoverflow.com/help/on-topic, in this case, a software algorithm to add an item to a dynamic unsorted array

This is chart we made in class about the runtimes of operations on different data structures

The question I have is about the runtime for inserting(or adding) a value into the dynamic unsorted array. Here is our code for doing this

 public void insert(E value) {
    ensureCapacity(size + 1);
    elementData[size] = value;
    size++;
}
  private void ensureCapacity(int capacity) {
    if (capacity > elementData.length) {
        int newCapacity = elementData.length + 100;
        if (capacity > newCapacity) {
            newCapacity = capacity;
        }
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
}

I understand how this could be interpreted as O(n). The ensureCapacity function is technically apart of the operations that consist of insert and then with runtime analysis, https://academics.tjhsst.edu/compsci/CS2C/U2/bigoh.html, you would say that the worst case of the two branches is when every element of the original array is copied into the new array which is an O(n) operation. So the worst case or big oh of the whole function is O(n)

Could an argument be made for amortized O(1) time as well(What is amortized analysis of algorithms?) because each time you resize, you have to wait a specific amount of time before the next resize?

In that chart, would O(1) also make sense then?


回答1:


No.

"Amortized O(1) time" means a very specific thing - it means that the cost of inserting n items, one at a time, is O(n). It is not enough to say that "the things that take a long time don't happen very often" - you do actually have to analyze the algorithm mathematically.

This particular case (inserting an item into an array, or resizing it if full) is a well-known one. As it turns out, if you resize the array by a constant factor (e.g. doubling it each time it's full) then this operation is amortized O(1). If you add a fixed number of elements (e.g. adding 100 each time it's full) then it's still amortized O(n), because it takes O(n2) time to add n elements individually.



来源:https://stackoverflow.com/questions/28377546/more-appropriate-to-say-amortized-o1-vs-on-for-insertion-into-unsorted-dynam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!