Dynamic Array--Data Structure

来源:互联网 发布:知乎 英国公爵 编辑:程序博客网 时间:2024/06/06 05:54

Three types of Array:

Static:int my_array[100];

Semi-Dynamic: int *my_array = new int[size]; (only if we know the max size)

If the max size is unknown, we use Dynamic Array.


Dynamic Array operations:

Get(i): returns element at location i*.

Set(i, val): Sets element i to Val*.

PushBack(val): Adds Val to the end.

Remove(i): removes element at location i

Size(): the number of elements.

   

Dynamic Array Resizing:

If the size of an array is 2,after operation "pushback(a) + pushback(b)". There is no more space at this time。An error will happen if operating "pushback(c)",so we need to create a double size array and copy current data into it, then the operation of "pushback(c)" will be executed。We must create a double size array and copy the current data again when the current array has no space to use. Doing it repeatly until all data has been stored. 


Time complexity of Runtime:

Get(i)                O(1)

Set(i, val)          O(1)

PushBack(val)  O(n)

Remove(i)         O(n)

Size()                O(1)


Common Implementations:

C++ : Vector

JAVA : ArryList

Python: List (the only kind of array)


Three ways to do analysis for amortized cost: 

(but nothing change in the code: runtime analysis only)

1, Aggregate method (brute-force sum)

2, Banker's method (tokens )

3, Physicist's method (potential function)


Summary:

1, Unlike static arrays, dynamic arrays can be resized. 

2, Appending a new element to a dynamic array is often constant time, but can take O(n).

3, Some space is wasted, but no more than half.




原创粉丝点击