You are on page 1of 20

1

Vectors
Outline and Required Reading: Vectors ( 5.1)

COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Sequence ADT
Sequence
general purpose linear ADT with methods for accessing, inserting, and removing arbitrary elements Examples: Vector, List, Full Sequence

Stacks, Queues, Deques restricted sequences with methods for


accessing, inserting, and removing only first and/or last element.

C B A
Stack

A B C

A B C

A B C

Queue

Deque

Sequence

Vector ADT
Vector sequence that supports random access/insertion/removal
of its elements by their rank

Rank

integer that specifies the number of elements, in a given sequence, before the element in question
abstraction of the concept of index in arrays the rank of an element may change whenever the sequence is

updated (e.g. an element added/removed)

Rank: n Rank: n+1

A B C

NOTE: Vector does NOT have to be implemented using arrays.

Vector ADT: Interface


Fundamental Methods
(Transformers) public Object elementAtRank(int k);
/* return the element of the vector with rank k */ /* error if k<0 or ksize()=n current # of elements */

public Object replaceAtRank(int k, Object e));


/* replace with e the element at rank k and return it */ /* error if k<0 or k size()=n current # of elements */

public void insertAtRank(int k, Object e);


/* insert a new element e so that it has rank k */ /* error if k<0 or k>size()=n current # of elements */ /* rank of all subsequent elements will increase */

public Object removeAtRank(int k);


/* remove from the element at rank k */ /* error if k<0 or k size()=n current # of elements */ /* rank of all subsequent elements will decrease */

Supporting Methods
(Observers)

public int size();


/* return the # of objects in the vector */

public boolean isEmpty();


/* return true if the vector is empty */

Vector ADT: Interface (cont.)


Vector Information Hiding
Vector ADT
e.g. Array
1) make room for new elem. 2) place new e at A[i]

Interface
elementAtRank() replaceAtRank()

insertAtRank(i,e)

insertAtRank()
removeAtRank

invisible to the user !!!

Vector Exceptions
ArrayIndexOutOfBoundsException InvalidRankException

Vector ADT: Array-Based Implementation


Trivial Array-Based use array A of size N (> expected # of elements) and store element with rank k at A[k] Implementation
V(i) = A[i]

rank of V = index of A

Drawback

costly! shifting of elements required on every insertion and removal

shifting

removal at rank=1

insertion at rank=1

shifting

Vector ADT: Performance of Array-Based Implement.


Run Times
Method size isEmpty elementAtRank insertAtRank removeAtRank Time O(1) O(1) O(1) O(n) O(n) AverageTime (1) (1) (1) (n) (n)

Space Usage Poor! Poor O(N), where Nn General Note problems with fixed array size
(space may be wasted or may be insufficient)

NOTE: run times of insertFirst() and insertLast() can be reduced to O(1) with circular array . However, the limited-capacity problem still remains.

Vector ADT: Implementing Deques with Vectors


Vector Acting as a Restricted Sequence
implementation of a Stack/Queue/Deque with an already existing Vector very simple NOTE: opposite does not apply !

Deque Method
Deque

Vector Method size() isEmpty() elementAtRank(0) elementAtRank(size()-1) insertAtRank(0,e) insertAtRank (size(), e) removeAtRank(0) removeAtRank(size()-1)

Time O(1) O(1) O(1) O(1) O(n) O(1) O(n) O(1)

A B C
Vector

size() isEmpty() first() last() insertFirst(e) insertLast(e) removeFirst() removeLast()

Vector ADT: Extensible Array Implementation


Extensible Array efficient tool for dealing with array overflows
(when n=N and method insertAtRank() is called) steps involved (1) allocate a new larger array (2) copy old elements to new array (3) reassign old reference to the array

A B
step (1)

A B
step (2)

A
step (3)

growing array strategies


(a) fixed increment: newCapacity=oldCapacity+C (b) doubling: newCapacity=2*oldCapacity

10

Vector ADT: Extensible Array Implementation (cont.)


Run Times in non-trivial to find a single method may have different run times depending on the current Extensible Arrays
array occupancy if n<N insertAtRank(n) runs at O(1) time if n=N insertAtRank(n) runs at O(N) time (first, all N elements must be copied to the new array)

when array is not full insert at O(1) cost

when array is full insert at O(N) cost

11

Vector ADT: Extensible Array Implementation (cont.)


Run Times in Extensible Arrays with Fixed Increments Strategy Run Times in Extensible Arrays with Doubling Strategy

n 2n On every capacity increase, next n inserts run at O(1) cost

On every capacity increase, next C inserts run at O(1) cost.

Which strategy would be better, overall?

Amortization Technique useful analysis tool when some method


calls are more expensive than others, we should average out the costs over the total number of calls

12

Vector ADT: Extensible Array Implementation (cont.)


Extensible Array with Fixed Increments
Assume: ! ! ! ! ! there are n=A+kC elements to be inserted at the end of a vector; A initial size of the extensible array C capacity increment value total number of capacity increases: k total number of copy operations: A + (A+C) + (A+2C) + + (A+(k-1)C) = = kA + C(1+2+..+(k-1)) = = Ak + Ck(k-1)/2 hence, the total run time of push method over n elements is: Ak + Ck(k-1)/2 (k2) = (((n-A)/C)2) = (n2) ! The amortized (average) time of a push operation is O(n) ! see Proposition 5.3 in the textbook

Accordingly:

13

Vector ADT: Extensible Array Implementation (cont.)

1st call for insertAtRank(size()) on full array A


A copy operations

2st call for insertAtRank(size()) on full array (more costly than previous) 3rd call for insertAtRank(size()) on full array (more costly than previous)

C
(A+C) copy operations

(A+2C) copy operations

14

Vector ADT: Extensible Array Implementation (cont.)


Extensible Array with Doubling Assume: ! ! there are n=2k elements to be inserted at the end of a vector; 1 initial size of the extensible array

see Proposition 5.2 in the textbook

Accordingly: ! ! total number of capacity increases: k total number of copy operations: 1 + 2 + 4 + + 2k-1 = = 2k - 1 = =n-1 hence, the total run time of push method over n elements is (i.e. total run time of n calls of push method): n - 1 (n) The amortized (average) time of a push operation is O(1) !

15

Vector ADT: Linked List Implementation


Advantages of SLL Implementation
(1) shifting of elements during insert and remove operations avoided (2) unlimited capacity all operations will require O(n) time (worst case) as they all involve walking through the list in order to find item at rank k ! use of Doubly LL enables faster walk through splitting, but RT still O(n)

Disadvantage of SLL Implementation

start from head if rank < n/2


A1 A2

start from tail if rank < n/2

An

head

tail

16

Vector ADT: Linked List Implementation


/* DLL implementation of nodeAtRank(int r) */ public DLLNode nodeAtRank(int r) { DLNode node; if (r <= size()/2) { /* scan forward from header */
O(n/2)

node = header.getNext(); for (int i=0; i < r; i++) { node = node.getNext(); };

} else {

/* scan backward from trailer */ node = trailer.getPrev(); for (int i=0; i < size()-r-1 ; i++) { node = node.getPrev(); };
O(n/2)

} return node;

17

Vector ADT: Performance of Linked List Implement.


Run Times Poor! Poor In general, LL is not a suitable data structure for
ADTs with random access to their elements. Method size isEmpty elementAtRank insertAtRank removeAtRank Time O(1) O(1) O(n) O(n) O(n)

Space Usage Good! Good O(n), where n the actual number of elements in
the vector.

General Note With LLs the cost of shifting is avoided, but a new cost
of walking through the list to find elements by rank is added; overall, LL implementation is worse!

18

Vector ADT: What Standard Java Offers!?


Vector Class in java.util.* [ from: http://java.sun.com/j2se/1.3/docs/api/java/util/Vector.html ]
! The Vector class implements a growable array of objects. ! Like an array, it contains components that can be accessed using an integer

index. However, the size of a Vector can grow or shrink as needed


Constructor Summary Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. Vector(int initialCapacity) Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. Vector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the specified initial capacity and capacity increment.

19

Vector ADT: What Standard Java Offers!? (cont.)


capacityIncrement ! The amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity. ! If the capacity increment is less than or equal to zero, the capacity of the vector is doubled each time it needs to grow. Vectors vs. Arrays ! Vectors automatically increase their capacity, should our program need room for more elements ". ! Vectors have built-in methods to accomplish many of the common tasks that otherwise we would have to design on our own if using arrays ". (e.g. insertElementAt(e,k), removeElementAt(k), ) ! The base type of a vector is always the type Object #, while the base type of an array can be of any type. (If we want to store values of a primitive type in a Vector, we would need to use a wrapper class for the primitive type.)

20

Vector ADT: Questions

Q.1 (textbook R-5.2) Describe how we could implement a Stack class (interface) using an already existing Vector class? Q.2 (textbook C-5.13) Discuss another possible implementation of the Deque ADT using the Vector ADT, that is different from the one discussed in class. Q.3 (textbook C-5.5) Q.4 (textbook C-5.14)

You might also like