0% found this document useful (0 votes)
16 views120 pages

Part1 Array

1. Arrays can be represented in memory as contiguous blocks with an overhead of a few bytes to store the starting address. 2. Multidimensional arrays can be represented as arrays of arrays, with each row stored in a separate block of memory. 3. Stacks follow the LIFO principle and are commonly used to match parentheses in expressions by tracking opening and closing pairs.

Uploaded by

王弘旻
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views120 pages

Part1 Array

1. Arrays can be represented in memory as contiguous blocks with an overhead of a few bytes to store the starting address. 2. Multidimensional arrays can be represented as arrays of arrays, with each row stored in a separate block of memory. 3. Stacks follow the LIFO principle and are commonly used to match parentheses in expressions by tracking opening and closing pairs.

Uploaded by

王弘旻
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 120

Arrays

1
1D Array Representation In C++
Memory

a b c d

start

• 1-dimensional array x = [a, b, c, d]


• map into contiguous memory locations

• location(x[i]) = start + i
2
Space Overhead
Memory

a b c d

start

space overhead = 4 bytes for start

(excludes space needed for the elements


of x)
3
2D Arrays

The elements of a 2-dimensional array a


declared as:
int [][]a = new int[3][4];
may be shown as a table
a[0][0] a[0][1] a[0][2] a[0][3]
a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]
4
Rows Of A 2D Array

a[0][0] a[0][1] a[0][2] a[0][3] row 0


a[1][0] a[1][1] a[1][2] a[1][3] row 1
a[2][0] a[2][1] a[2][2] a[2][3] row 2

5
Columns Of A 2D Array

a[0][0] a[0][1] a[0][2] a[0][3]


a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]

column 0 column 1 column 2 column 3

6
2D Array Representation In C++
2-dimensional array x
a, b, c, d
e, f, g, h
i, j, k, l
view 2D array as a 1D array of rows
x = [row0, row1, row 2]
row 0 = [a,b, c, d]
row 1 = [e, f, g, h]
row 2 = [i, j, k, l]
and store as 4 1D arrays
7
2D Array Representation In C++
x[]

a b c d

e f g h

i j k l

8
Space Overhead
x[]

a b c d

e f g h

i j k l

space overhead = overhead for 4 1D arrays


= 4 * 4 bytes
= 16 bytes
= (number of rows + 1) x 4 bytes

9
Array Representation In C++
x[]

a b c d

e f g h

i j k l

• This representation is called the array-of-arrays representation.


• Requires contiguous memory of size 3, 4, 4, and 4 for the 4 1D
arrays.
• 1 memory block of size number of rows and number of rows
blocks of size number of columns

10
Row-Major Mapping
• Example 3 x 4 array:
abcd
efgh
i jkl
• Convert into 1D array y by collecting elements by
rows.
• Within a row elements are collected from left to right.
• Rows are collected from top to bottom.
• We get y[] = {a, b, c, d, e, f, g, h, i, j, k, l}
row 0 row 1 row 2 … row i 11
Locating Element x[i][j]
0 c 2c 3c ic

row 0 row 1 row 2 … row i

• assume x has r rows and c


columns
• each row has c elements
• i rows to the left of row i
• so ic elements to the left of x[i]
[0]
• so x[i][j] is mapped to position 12
Space Overhead

row 0 row 1 row 2 … row i

4 bytes for start of 1D array +


4 bytes for c (number of columns)
= 8 bytes

13
Disadvantage

Need contiguous memory of size


rc.

14
Column-Major Mapping
abcd
efgh
i jkl
• Convert into 1D array y by collecting
elements by columns.
• Within a column elements are collected
from top to bottom.
• Columns are collected from left to right.
• We get y = {a, e, i, b, f, j, c, g, k, d, h, l}
15
Matrix
Table of values. Has rows and columns, but
numbering begins at 1 rather than 0.
a b c d row 1
efgh row 2
i jkl row 3
• Use notation x(i,j) rather than x[i][j].
• May use a 2D array to represent a matrix.

16
Shortcomings Of Using A 2D
Array For A Matrix

• Indexes are off by 1.


• C++ arrays do not support matrix
operations such as add, transpose, multiply,
and so on.
– Suppose that x and y are 2D arrays. Can’t do x
+ y, x –y, x * y, etc. in Java.
• Develop a class Matrix for object-oriented
support of all matrix operations.
17
Diagonal Matrix

An n x n matrix in which all nonzero


terms are on the diagonal.

18
Diagonal Matrix
1000
0200
0030
0004

• x(i,j) is on diagonal iff i = j


• number of diagonal elements in an n x n matrix is n
• non diagonal elements are zero
• store diagonal only vs n2 whole

19
Lower Triangular Matrix
An n x n matrix in which all nonzero terms are
either on or below the diagonal.
100 0
230 0
456 0
7 8 9 10
• x(i,j) is part of lower triangle iff i >= j.
• number of elements in lower triangle is 1 + 2 + … + n = n(n+1)/2.
• store only the lower triangle

20
Array Of Arrays Representation
x[]

2 3

4 5 6

7 8 9 l0

Use an irregular 2-D array … length of rows is


not required to be the same.
21
Creating And Using An Irregular
Array
// declare a two-dimensional array variable
// and allocate the desired number of rows
int ** irregularArray = new int* [numberOfRows];

// now allocate space for the elements in each row


for (int i = 0; i < numberOfRows; i++)
irregularArray[i] = new int [length[i]];

// use the array like any regular array


irregularArray[2][3] = 5;
irregularArray[4][6] = irregularArray[2][3] + 2;
irregularArray[1][1] += 3; 22
Map Lower Triangular Array Into A 1D Array

Use row-major order, but omit terms that


are not part of the lower triangle.

For the matrix


100 0
230 0
456 0
7 8 9 10
we get
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 23
Index Of Element [i][j]

0 1 3 6
r 1 r2 r3 … row i

• Order is: row 1, row 2, row 3, …


• Row i is preceded by rows 1, 2, …, i-1
• Size of row i is i.
• Number of elements that precede row i is
1 + 2 + 3 + … + i-1 = i(i-1)/2
• So element (i,j) is at position i(i-1)/2 + j -1
of the 1D array. 24
Stacks

• Linear list.
• One end is called top.
• Other end is called bottom.
• Additions to and removals from the top end
only.
25
Stack Of Cups
top F

top E E

D D

C C

B B

bottom A bottom A

• Add a cup to the stack.


• Remove a cup from new stack.
• A stack is a LIFO list.

26
Parentheses Matching
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)
– Output pairs (u,v) such that the left parenthesis at
position u is matched with the right parenthesis at v.
• (2,6) (1,13) (15,19) (21,25) (27,31) (0,32) (34,38)
• (a+b))*((c+d)
– (0,4)
– right parenthesis at 5 has no matching left
parenthesis
– (8,12)
left parenthesis at 7 has no matching right parenthesis

27
Parentheses Matching
• scan expression from left to right
• when a left parenthesis is encountered, add
its position to the stack
• when a right parenthesis is encountered,
remove matching position from stack

28
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)

2
1
0

29
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)

15
1
0 (2,6) (1,13)

30
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)

21
1
0 (2,6) (1,13) (15,19)

31
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)

27
1
0 (2,6) (1,13) (15,19) (21,25)

32
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)

34
0 (2,6) (1,13) (15,19) (21,25)(27,31) (0,32)

• and so on 33
Method Invocation And Return
public void a()
{ …; b(); …}
public void b()
{ …; c(); …} return address in d()
public void c() return address in c()
{ …; d(); …} return address in e()
public void d() return address in d()
{ …; e(); …}
return address in c()
return address in b()
public void e()
return address in a()
{ …; c(); …} 34
Towers Of Hanoi/Brahma

4
3
2
1

A B C
• 64 gold disks to be moved from tower A to tower C
• each tower operates as a stack
35
• cannot place big disk on top of a smaller one
Towers Of Hanoi/Brahma

3
2
1

A B C
• 3-disk Towers Of Hanoi/Brahma
36
Towers Of Hanoi/Brahma

2
1 3

A B C
• 3-disk Towers Of Hanoi/Brahma
37
Towers Of Hanoi/Brahma

1 2 3

A B C
• 3-disk Towers Of Hanoi/Brahma
38
Towers Of Hanoi/Brahma

3
1 2

A B C
• 3-disk Towers Of Hanoi/Brahma
39
Towers Of Hanoi/Brahma

3
2 1

A B C
• 3-disk Towers Of Hanoi/Brahma
40
Towers Of Hanoi/Brahma

3 2 1

A B C
• 3-disk Towers Of Hanoi/Brahma
41
Towers Of Hanoi/Brahma

2
3 1

A B C
• 3-disk Towers Of Hanoi/Brahma
42
Towers Of Hanoi/Brahma

3
2
1

A B C
• 3-disk Towers Of Hanoi/Brahma
• 7 disk moves 43
Recursive Solution

A B C
• n > 0 gold disks to be moved from A to C using B
• move top n-1 disks from A to B using C
44
Recursive Solution

A B C
• move top disk from A to C
45
Recursive Solution

A B C
• move top n-1 disks from B to C using A
46
Recursive Solution

B C
A
• moves(n) = 0 when n = 0
• moves(n) = 2*moves(n-1) + 1 = 2n-1 when n > 0

47
Towers Of Hanoi/Brahma

• moves(64) = 1.8 * 1019 (approximately)


• Performing 109 moves/second, a computer would take about
570 years to complete.
• At 1 disk move/min, the monks will take about 3.4 * 1013 years.

48
Algorithm
Hanoi(N, Src, Aux, Dst)
if N is 0
exit
else
Hanoi(N - 1, Src, Dst, Aux)
Move from Src to Dst
Hanoi(N - 1, Aux, Src, Dst)

49
S(3, A,B,C)
S(2, A,C,B)
S(1, A,B,C)
S(0, A,C,B); A->C; S(0, B,A,C)
A->B
S(1, C,A,B)
S(0, C,B,A); C->B; S(0, A,C,B)
A-> C
S(2, B,A,C)
S(1, B,C,A)
S(0, B,A,C); B->A; S(0, C,B,A)
B->C
S(1, A,B,C)
S(0, A,C,B); A->C; S(0, B,A,C)
50
Method Invocation And Return
public void a()
{ ..; b();..
return }
public void b()
{ ..; c();.. return}
public void c()
{ ..; d(); ..return}
public void d() return Hanoi(1,A,B,C)
{ …; return} return Hanoi(2,A,C,B)
return Hanoi(3,A,B,C)
51
Rat In A Maze

52
Rat In A Maze

• Move order is: right, down, left, up


• Block positions to avoid revisit.
53
Rat In A Maze

• Move order is: right, down, left, up


• Block positions to avoid revisit.
54
Rat In A Maze

• Move backward until we reach a square from which a forward move is


possible.
55
Rat In A Maze

• Move down.
56
Rat In A Maze

• Move left.
57
Rat In A Maze

• Move down.
58
Rat In A Maze

• Move backward until we reach a square from which a forward move is


possible.
59
Rat In A Maze

• Move backward until we reach a square from which a


forward move is possible.
60
• Move downward.
Rat In A Maze

• Move right.
• Backtrack. 61
Rat In A Maze

• Move downward.
62
Rat In A Maze

• Move right.
63
Rat In A Maze

• Move one down and then right.


64
Rat In A Maze

• Move one up and then right.


65
Rat In A Maze

• Move down to exit and eat cheese.


• Path from maze entry to current position operates as a stack.

66
Stacks

– Standard operations:
• IsEmpty … return true iff stack is empty
• Top … return top element of stack
• Push … add an element to the top of the stack
• Pop … delete the top element of the stack

67
Stacks

– Use a 1D array to represent a stack.


– Stack elements are stored in stack[0] through
stack[top].

68
Stacks
a b c d e
0 1 2 3 4 5 6

– stack top is at element e


– IsEmpty() => check whether top >= 0
• O(1) time
– Top() => If not empty return stack[top]
• O(1) time

69
Derive From arrayList
a b c d e
0 1 2 3 4 5 6

– Push(theElement) => if array full (top ==


capacity – 1) increase capacity and then add
at stack[top+1]
– O(capacity) time when full; otherwise O(1)
– pop() => if not empty, delete from stack[top]
– O(1) time
70
Background of C++
• Template
• Constructor

71
Template Class
#include <iostream>
using namespace std;

// definition of function template maximum


template < class T > // or template < typename T >
T maximum( T value1, T value2, T value3)
{
T max = value1;

if( value2 > max )


max = value2;
if( value3 > max )
max = value3;

return max;
}

72
How to use template?
int main()
{
int int1,int2,int3;

cout << "Input three integer values:";


cin >> int1 >> int2 >> int3;
cout << "The maximum integer value is: "
<< maximum(int1,int2,int3) << endl;

double double1,double2,double3;
cout << "Input three double values:";
cin >> double1 >> double2 >> double3;
cout << "The maximum integer value is: "
<< maximum(double1,double2,double3) << endl;

char char1,char2,char3;
cout << "Input three characters:";
cin >> char1 >> char2 >> char3;
cout << "The maximum character value is: "
<< maximum(char1,char2,char3) << endl;

system("pause");
return 0;
}
73
Constructor
#ifndef POINT_H
#define POINT_H
class Point {
public:Point(); // parameterless default constructor
Point(int new_x, int new_y);
private:
int x;
int y;
};
#endif

74
Implementation
Point::Point() { // default constructor
x = 0;
y = 0; }

//constrctor with parameters


Point::Point(int new_x, int new_y) {
x = new_x;
y = new_y;
}

75
How to use constructor?
Point p; // calls our default constructor

Point q(10,20); // calls constructor with parameters

Point* r = new Point(); // calls default constructor

Point s = p; // our default constructor has not been called.

76
The Class Stack
template<class T>
class Stack
{
public:
Stack(int stackCapacity = 10);
~Stack() {delete [] stack;}
bool IsEmpty() const;
T& Top() const;
void Push(const T& item);
void Pop();
private:
T *stack; // array for stack elements
int top; // position of top element
int capacity; // capacity of stack array
77
};
Constructor
template<class T>
Stack<T>::Stack(int stackCapacity)
:capacity(stackCapacity)
{
if (capacity < 1)
throw “Stack capacity must be > 0”;
stack = new T[capacity];
top = -1;
}

78
IsEmpty

template<class T>
inline bool Stack<T>::IsEmpty() const
{return top == -1}

79
Top

template<class T>
inline T& Stack<T>::Top() const
{
if (IsEmpty())
throw “Stack is empty”;
return stack[top];
}

80
Push
a b c d e
0 1 2 3 4 top
template<class T>
void Stack<T>::Push(const T& x)
{// Add x to the stack.
if (top == capacity - 1)
{ChangeSize1D(stack, capacity,
2*capacity);
capacity *= 2;
}
// add at stack top
stack[++top] = x; 81

}
Pop
a b c d e
0 1 2 3 4 top
void Stack<T>::Pop()
{
if (IsEmpty())
throw “Stack is empty. Cannot delete.”;
stack[top--].~T(); // destructor for T
}

82
Queues

• Linear list.
• One end is called front.
• Other end is called rear.
• Additions are done at the rear only.
• Removals are made from the front only.

83
Bus Stop Queue

Bus
Stop

front rear rear rear rear


rear

84
Bus Stop Queue

Bus
Stop

front rear rear


rear

85
Bus Stop Queue

Bus
Stop

front rear
rear

86
Bus Stop Queue

Bus
Stop

front rear
rear

87
Revisit Of Stack Applications
• Applications in which the stack cannot
be replaced with a queue.
– Parentheses matching.
– Towers of Hanoi.
– Method invocation and return.
• Application in which the stack may be
replaced with a queue.
– Rat in a maze.
• Results in finding shortest path to exit.

88
Wire Routing

89
Lee’s Wire Router
start pin

end pin

Label all reachable squares 1 unit from start. 90


Lee’s Wire Router
start pin

end pin
1 1

Label all reachable unlabeled squares 2 units


from start. 91
Lee’s Wire Router
start pin

end pin 2 2
1 1 2
2 2

Label all reachable unlabeled squares 3 units


from start. 92
Lee’s Wire Router
start pin
3 3
end pin 2 2
1 1 2
2 2
3 3

Label all reachable unlabeled squares 4 units


93
from start.
Lee’s Wire Router
start pin 4
3 3
end pin 2 2
1 1 2
2 2
3 4 3 4
4 4

Label all reachable unlabeled squares 5 units


94
from start.
Lee’s Wire Router
5
start pin 4 5
3 3
end pin 2 2
1 1 2
2 2
3 4 3 4 5
4 4 5
5 5

Label all reachable unlabeled squares 6 units


95
from start.
Lee’s Wire Router
6 5 6
start pin 4 5
3 3
end pin 2 2
1 1 2
2 2 6
3 4 3 4 5 6
4 4 5 6
5 6 5 6
6

End pin reached. Traceback. 96


Lee’s Wire Router
6 5 6
start pin 4 5
3 3
end pin 2 2
1 1 2
2 2 6
3 4 3 4 5 6
4 4 5 6
5 6 5 6
6

End pin reached. Traceback. 97


Queue Operations

– IsEmpty … return true iff queue is empty


– Front … return front element of queue
– Rear … return rear element of queue
– Push … add an element at the rear of the queue
– Pop … delete the front element of the queue

98
Queue in an Array

– Use a 1D array to represent a queue.


– Suppose queue elements are stored with the
front element in queue[0], the next in queue[1],
and so on.

99
Derive From arrayList
a b c d e
0 1 2 3 4 5 6

 Pop() => delete queue[0]


– O(queue size) time
 Push(x) => if there is capacity, add at right
end
– O(1) time

100
O(1) Pop and Push

– to perform each opertion in O(1) time (excluding


array doubling), we use a circular representation.

101
Custom Array Queue
• Use a 1D array queue.

queue[]

• Circular view of array.

[2] [3]

[1] [4]

[0] [5] 102


Custom Array Queue
• Possible configuration with 3 elements.

[2] [3]
A B

[1] C [4]

[0] [5]

103
Custom Array Queue
• Another possible configuration with 3 elements.

[2] [3]

[1] C [4]
B A
[0] [5]

104
Custom Array Queue
• Use integer variables front and rear.
– front is one position counterclockwise from
first element
– rear gives position of last element

[2] [3] [2] [3]


A B
front rear rear
front
[1] C [4] [1] C [4]

B A
[0] [5] [0] [5] 105
Push An Element
• Move rear one clockwise.

[2] [3]
A B rear
front
[1] C [4]

[0] [5]

106
Push An Element
• Move rear one clockwise.
• Then put into queue[rear].

[2] [3]
A B
front
[1] C [4]

D
[0] [5]

rear 107
Pop An Element
• Move front one clockwise.

[2] [3]
A B rear
front
[1] C [4]

[0] [5]

108
Pop An Element
• Move front one clockwise.
• Then extract from queue[front].

front [2] [3]


A B rear

[1] C [4]

[0] [5]

109
Moving rear Clockwise
• rear++;
if (rear = = capacity) rear = 0;
[2] [3]
A B rear
front
[1] C [4]

[0] [5]

• rear = (rear + 1) % capacity;


110
Empty That Queue
[2] [3]

rear
front
[1] C [4]
B A
[0] [5]

111
Empty That Queue
[2] [3]

rear
[1] C [4]
B
[0] [5]

front

112
Empty That Queue
[2] [3]

rear
[1] C [4]

[0] [5]

front

113
Empty That Queue
[2] [3]

rear
[1] [4]

front [0] [5]


• When a series of removes causes the queue to become empty, front = rear.
• When a queue is constructed, it is empty.
• So initialize front = rear = 0.

114
A Full Tank Please
[2] [3]

rear
front
[1] C [4]
B A
[0] [5]

115
A Full Tank Please
[2] [3]
rear
D
front
[1] C [4]
B A
[0] [5]

116
A Full Tank Please
[2] [3] rear
D E
front
[1] C [4]
B A
[0] [5]

117
A Full Tank Please
[2] [3]
D E
front
[1] C F [4]
B A rear
[0] [5]

• When a series of adds causes the queue to become full, front = rear.
• So we cannot distinguish between a full queue and an empty queue!

118
Ouch!!!!!
• Remedies.
– Don’t let the queue get full.
• When the addition of an element will cause the queue to
be full, increase array size.
• This is what the text does.
– Define a boolean variable lastOperationIsPush.
• Following each push set this variable to true.
• Following each pop set to false.
• Queue is empty iff (front == rear) && !
lastOperationIsPush
• Queue is full iff (front == rear) && lastOperationIsPush
119
Ouch!!!!!
• Remedies (continued).
– Define an integer variable size.
• Following each push do size++.
• Following each pop do size--.
• Queue is empty iff (size == 0)
• Queue is full iff (size == arrayLength)
– Performance is slightly better when first strategy is
used.

120

You might also like