Dynamic Array--Data Structure

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.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值