Professional Documents
Culture Documents
gif
Source: http://math.hws.edu/eck/cs124/javanotes3/c8/fig4.gif
Insertion Sort
for (int i = 1; i < n; i++)
{// insert a[i] into a[0:i-1]
int t = a[i];
int j;
for (j = i - 1; j >= 0 && t < a[j]; j--)
a[j + 1] = a[j];
a[j + 1] = t;
}
Complexity
Space/Memory
Time
Count a particular operation
Count number of steps
Asymptotic complexity
Comparison Count
for (int i = 1; i < n; i++)
{// insert a[i] into a[0:i-1]
int t = a[i];
int j;
for (j = i - 1; j >= 0 && t < a[j]; j--)
a[j + 1] = a[j];
a[j + 1] = t;
}
Comparison Count
Pick an instance characteristic … n
For insertion sort, pick n = number of
elements to be sorted.
Determine count as a function of this
instance characteristic.
Comparison Count
for (j = i - 1; j >= 0 && t < a[j]; j--)
a[j + 1] = a[j];
x = sum(a[], n);
i=1
i=2
…
1+2+3+…+n = n(n-1)/2
Space Complexity
O(n) total
O(1) additional space
Source: https://en.wikipedia.org/wiki/Insertion_sort#/media/File:Insertion-sort-example-300px.gif
Asymptotic Complexity of
Insertion Sort
O(n2)
What does this mean?
Complexity of Insertion Sort
Time or number of operations does not
exceed c.n2 on any input of size n (n
suitably large)(c constant).
Actually, the worst-case time is Θ(n2)
and the best-case is Θ(n)
So, the worst-case time is expected to
quadruple each time n is doubled
Complexity of Insertion Sort
Is O(n2) too much time?
Is the algorithm practical?
Practical Complexities
109 instructions/second
2 3
n n nlogn n n
1000 1mic 10mic 1milli 1sec
E.g. 2n to n3
To-do
Read:
– https://en.wikipedia.org/wiki/Big_O_notation
Do:
– Create GitHub (or similar) account
– Insert 0 into 1 2 3 4 5 – Count Steps
– Insert 10 into 1 2 3 4 5 – Count Steps
Implement (ungraded):
– Insertion Sort (C++/Java)
– Sort a sorted sequence/reversely sorted sequence
(n=1000,1000000), what’s the difference in
runtime?
Performance Measurement
Performance Analysis
Paper and pencil.
MAIN
L2
L1
ALU R
8-32 32KB ~512KB ~512MB
1C 2C 10C 100C
Limitations of Analysis
What do we need?
Performance Measurement Needs
programming language
e.g. C++/Java
working program
Insertion Sort
computer
compiler and options to use
gcc –O2
Performance Measurement Needs
data to use for measurement
worst-case data
best-case data
average-case data
trueElapsedTime =
finishTime - startTime +- 100 ticks
data object
daysOfWeek = {S,M,T,W,Th,F,Sa}
Data Object
369
3 is more significant than 6
3 is immediately to the left of 6
9 is immediately to the right of 6
Data Structure
relationships
e0 is the zero’th (or front) element
en-1 is the last element
ei immediately precedes ei+1
Linear List Examples/Instances
Students in COP3530 =
(Jack, Jill, Abe, Henry, Mary, …, Judy)
Exams in COP3530 =
(exam1, exam2, exam3)
L = (a,b,c,d,e)
size = 5
Linear List Operations—get(theIndex)
get element with given index
L = (a,b,c,d,e)
get(0) = a
get(2) = c
get(4) = e
get(-1) = error
get(9) = error
Linear List Operations—
indexOf(theElement)
L = (a,b,d,b,a)
indexOf(d) = 2
indexOf(a) = 0
indexOf(z) = -1
Linear List Operations—
erase(theIndex)
L = (a,b,c,d,e,f,g)
erase(2) removes c
and L becomes (a,b,d,e,f,g)
L = (a,b,c,d,e,f,g)
L = (a,b,c,d,e,f,g)
L = (a,b,c,d,e,f,g)
a b c d e
0 1 2 3 4 5 6
L = (a, b, c, d, e)
Store element i of list in element[i].
Right To Left Mapping
e d c b a
Mapping That Skips Every Other
Position
a b c d e
Wrap Around Mapping
d e a b c
Representation Used In Text
a b c d e
0 1 2 3 4 5 6 listSize = 5
insert(1,g)
listSize = 6
a g b c d e
Data Type Of Array element[]
Data type of list elements is unknown.
a b c d e f
a b c d e f
#include <algorithm>
a b c d e f
template<class T>
void changeLength1D(T*& a, int oldLength,
int newLength)
{
1 if (newLength < 0)
throw illegalParameterValue();
element[6]
a b c d e f
arrayList of text … c = 2
To-do
Practice:
– https://www.hackerrank.com/
challenges/cpp-input-and-
output
More on insertion sort:
– https://en.wikipedia.org/wiki/I
nsertion_sort
The Class arrayList
// additional method
int capacity() const {return arrayLength;}
The Class arrayList
protected:
void checkIndex(int theIndex) const;
// throw illegalIndex if theIndex invalid
T* element; // 1D array to hold list elements
int arrayLength; // capacity of the 1D array
int listSize; // number of elements in list
};
A Constructor
template<class T>
arrayList<T>::arrayList(int initialCapacity)
{// Constructor.
if (initialCapacity < 1)
{ostringstream s;
s << "Initial capacity = "
<< initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
arrayLength = initialCapacity;
element = new T[arrayLength];
listSize = 0;
}
Copy Constructor
template<class T>
arrayList<T>::arrayList(const arrayList<T>&
theList)
{// Copy constructor.
arrayLength = theList.arrayLength;
listSize = theList.listSize;
element = new T[arrayLength];
copy(theList.element, theList.element +
listSize, element);
}
The Method checkIndex
template<class T>
void arrayList<T>::checkIndex(int theIndex) const
{// Verify that theIndex is between 0 and
// listSize - 1.
if (theIndex < 0 || theIndex >= listSize)
{ostringstream s;
s << "index = " << theIndex << " size = "
<< listSize;
throw illegalIndex(s.str());
}
}
The Method get
template<class T>
T& arrayList<T>::get(int theIndex) const
{// Return element whose index is theIndex.
// Throw illegalIndex exception if no such
// element.
checkIndex(theIndex);
return element[theIndex];
}
The Method indexOf
template<class T>
int arrayList<T>::indexOf(const T& theElement)
const
{// Return index of first occurrence of
theElement.
// search for theElement
int theIndex = (int) (find(element, element
+ listSize, theElement) - element);
// check if theElement was found
if (theIndex == listSize)
return -1; // not found
else return theIndex;
}
The Method erase
template<class T>
void arrayList<T>::erase(int theIndex)
{// Delete the element whose index is theIndex.
checkIndex(theIndex);
element[theIndex] = theElement;
listSize++;
}
The Method output
template<class T>
void arrayList<T>::output(ostream& out) const
{// Put the list into the stream out.
copy(element, element + listSize,
ostream_iterator<T>(cout, " "));
}
Overloading <<
// overload <<
template <class T>
ostream& operator<<(ostream& out,
const arrayList<T>& x)
{x.output(out); return out;}
Iterators
vs
for (int i = 0; i < x.size(); i++)
examine(x.get(i));
Merits Of An Iterator
• it is often possible to implement the
++ and -- operators so that their
complexity is less than that of get
• many data structures do not have a
get by index method
• iterators provide a uniform way to
sequence through the elements of a
data structure
Linked Representation
a b c d e
c a e d b
firstNode
pointer (or link) in e is NULL
firstNode
NULL
a b c d e
NULL
a b c d e
?
chainNode(const T& element)
element
{this->element = element;}
NULL
a b c d e
checkIndex(0);
desiredNode = firstNode; // gets you to first node
return desiredNode−>element;
get(1)
firstNode
NULL
a b c d e
checkIndex(1);
desiredNode = firstNode−>next; // gets you to second node
return desiredNode−>element;
get(2)
firstNode
NULL
a b c d e
checkIndex(2);
desiredNode = firstNode−>next−>next; // gets you to third node
return desiredNode−>element;
get(5)
firstNode
NULL
a b c d e
NULL
a b c d e
erase(0)
deleteNode = firstNode;
firstNode = firstNode−>next;
delete deleteNode;
erase(2)
firstNode
NULL
b cc
a d e
beforeNode
first get to node just before node to be removed
beforeNode = firstNode−>next;
erase(2)
firstNode
null
a b c d e
beforeNode
null
a b c d e
beforeNode
NULL
f a b c d e
newNode
NULL
f a b c d e
newNode
firstNode = newNode;
One-Step insert(0,’f’)
firstNode
NULL
f a b c d e
newNode
a b c d e
beforeNode
• first find node whose index is 2
• next create a node and set its data and link fields
chainNode<char>* newNode = new chainNode<char>( ‘f’,
beforeNode−>next);
• finally link beforeNode to newNode
beforeNode−>next = newNode;
Two-Step insert(3,’f’)
firstNode newNode
f
NULL
a b c d e
beforeNode
beforeNode = firstNode−>next−>next;
beforeNode−>next = new chainNode<char>
(‘f’, beforeNode−>next);
To-do
Practice:
– https://www.hackerrank.com/domai
ns/cpp/introduction
Read more on iterators:
– http://www.cplusplus.com/referenc
e/iterator/
– http://www.cplusplus.com/referenc
e/iterator/iterator/
Read more on linked lists:
– https://en.wikipedia.org/wiki/Linked
_list
Reminder: Course Policy
NULL
a b c d e
NULL
a b c d e
Use chainNode
next (datatype chainNode<T>*)
element (datatype T)
The Class chain
template<class T>
class chain : public linearList<T>
{
public:
// constructors and destructor defined here
// ADT methods
bool empty() const {return listSize == 0;}
int size() const {return listSize;}
// other ADT methods defined here
protected:
void checkIndex(int theIndex) const;
chainNode<T>* firstNode;
int listSize;
};
Constructor
template<class T>
chain<T>::chain(int initialCapacity = 10)
{// Constructor.
if (initialCapacity < 1)
{ostringstream s;
s << "Initial capacity = "
<< initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
firstNode = NULL;
listSize = 0;
}
The Destructor
template<class T>
chain<T>::~chain()
{// Chain destructor. Delete all nodes
// in chain.
while (firstNode != NULL)
{// delete firstNode
chainNode<T>* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
firstNode The Method get
NULL
a b c d e
template<class T>
T& chain<T>::get(int theIndex) const
{// Return element whose index is theIndex.
checkIndex(theIndex);
// move to desired node
chainNode<T>* currentNode = firstNode;
for (int i = 0; i < theIndex; i++)
currentNode = currentNode->next;
return currentNode->element;
}
The Method indexOf
template<class T>
int chain<T>::indexOf(const T& theElement) const
{
// search the chain for theElement
chainNode<T>* currentNode = firstNode;
int index = 0; // index of currentNode
while (currentNode != NULL &&
currentNode->element != theElement)
{
// move to next node
currentNode = currentNode->next;
index++;
}
The Method indexOf
// make sure we found matching element
if (currentNode == NULL)
return -1;
else
return index;
}
Erase An Element
firstNode
NULL
a b c d e
erase(0)
deleteNode = firstNode;
firstNode = firstNode->next;
delete deleteNode;
Remove An Element
template<class T>
void chain<T>::erase(int theIndex)
{
checkIndex(theIndex);
chainNode<T>* deleteNode;
if (theIndex == 0)
{// remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
erase(2)
firstNode
null
a b c d e
beforeNode
deleteNode = p->next;
p->next = p->next->next;
}
listSize--;
delete deleteNode;
}
One-Step insert(0,’f’)
firstNode
NULL
f a b c d e
newNode
if (theIndex == 0)
// insert at front
firstNode = new chainNode<T>
(theElement, firstNode);
Two-Step insert(3,’f’)
firstNode newNode
f
NULL
a b c d e
beforeNode
beforeNode = firstNode->next->next;
beforeNode->next = new chainNode<char>
(‘f’, beforeNode->next);
Inserting An Element
else
{ // find predecessor of new element
chainNode<T>* p = firstNode;
for (int i = 0; i < theIndex - 1; i++)
p = p->next;
// insert after p
p->next = new chainNode<T>
(theElement, p->next);
}
listSize++;
}
Performance
50,000 operations of each type
Performance
50,000 operations of each type
headerNode
NULL
a b c d e
Empty Chain With Header Node
headerNode
NULL
Circular List
firstNode
a b c d e
Doubly Linked List
firstNode lastNode
NULL
NULL
a b c d e
Doubly Linked Circular List
firstNode
a b c d e
Doubly Linked Circular List With Header Node
headerNode
a b c d e
Empty Doubly Linked Circular List With Header Node
headerNode
The STL Class list
c a e d b
c a e d b
next 14
11 14 -1 8 0
element c a e d b
0 1 2 3 4 5 8 11 14
firstNode = 4
Still Drawn The Same
firstNode
-1
a b c d e
Memory Management
Linked system (C++ or simulated pointer)
requires:
• a way to keep track of the memory that is not
in use (i.e., a storage pool)
• way to allocate a node
C++ has the method new
• way to free a node that is no longer in use
C++ has the method delete
Garbage Collection
The system determines which nodes/memory are
not in use and returns these nodes (this memory)
to the pool of free storage.
c a e d b
firstNode
c a e dd be
firstNode
c a e d b Free
e Memory
d b
firstNode
firstNode
-1
a b c d e
a b c d
start
• location(x[i]) = start + i
Space Overhead
Memory
a b c d
start
a b c d
e f g h
i j k l
a b c d
e f g h
i j k l
a b c d
e f g h
i j k l
2 3
4 5 6
7 8 9 l0
0 1 3 6
r 1 r2 r3 … row i
http://www.cplusplus.com/doc/tutorial
/arrays/
https://en.wikipedia.org/wiki/Matrix_(
mathematics)
Don’t forget assignment 2
Reminder: Array Representation In C++
x[]
a b c d
e f g h
i j k l
Web analysis.
authority page … page that has many links to it
hub page … links to many authority pages
Web Page Matrix
n = 2 billion (and growing by 1 million a day)
n x n array of ints => 4* 1018 integers =
16* 1018 bytes (16 * 109 GB)
each page links to 10 (say) other pages on
average
on average there are 10 nonzero entries per row
space needed for nonzero elements is
approximately 20 billion x 4 bytes = 80 billion
bytes (80 GB)
Representation Of Unstructured
Sparse Matrices
Single linear list in row-major order.
scan the nonzero elements of the sparse matrix in row-
major order
each nonzero element is represented by a triple
(row, column, value)
the list of triples may be an array list or a linked list
(chain)
Single Linear List Example
00304 list =
00570 row 1 1 2 2 4 4
00000 column 3 5 3 4 2 3
02600 value 3 4 5 7 2 6
Array Linear List Representation
row 1 1 2 2 4 4
list = column 3 5 3 4 2 3
value 3 4 5 7 2 6
element 0 1 2 3 4 5
row 1 1 2 2 4 4
column 3 5 3 4 2 3
value 3 4 5 7 2 6
Chain Representation
Node structure.
row col
value next
Single Chain
row 1 1 2 2 4 4
list = column 3 5 3 4 2 3
value 3 4 5 7 2 6
1 3 1 5 2 3 2 4 4 2 4 3
3 4 5 7 2 6 NULL
firstNode
One Linear List Per Row
Node structure.
next
col value
Array Of Row Chains
NULL
3 3 5 4
00304 NULL
00570 3 5 4 7
00000 NULL
02600
NULL
2 2 3 6
row[]
Orthogonal List Representation
Node structure.
row col value
down next
Row Lists
1 3 3 1 5 4
N
00304
00570 2 3 5 2 4 7
N
00000
02600 NULL
4 2 2 4 3 6
N
Column Lists
1 3 3 1 5 4
N
00304
00570 2 3 5 2 4 7
00000
02600
4 2 2 4 3 6
N N
Orthogonal Lists
1 3 3 1 5 4
N N
00304
00570 2 3 5 2 4 7
N
00000
02600 NULL
4 2 2 4 3 6
N N N
row[]
Variations
2D array 1.97 ms
Single Array List 0.09 ms
One Chain Per Row 1.57 ms
Performance
Matrix Addition.
500 x 500 matrices with 1994 and 999 nonzero
elements
2D array 2.69 ms
Single Array List 0.13 ms
One Chain Per Row Not Measured
Stacks
• Linear list.
• One end is called top.
• Other end is called bottom.
• Additions to and removals from the top end
only.
Stack Of Cups
top F
top E E
D D
C C
B B
bottom A bottom A
template<class T>
class stack
{
public:
virtual ~stack() {}
virtual bool empty() const = 0;
virtual int size() const = 0;
virtual T& top() = 0;
virtual void pop() = 0;
virtual void push(const T& theElement) = 0;
};
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
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
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)
2
1
0
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)
15
1
0 (2,6) (1,13)
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)
21
1
0 (2,6) (1,13) (15,19)
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)
Example
• (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)
1
0 (2,6) (1,13) (15,19) (21,25) (27,31) (0,32)
• and so on
Sample application:
Evaluate an expression
• E.g. (((2+3)+4)*2)
• If parentheses are unbalanced Invalid
• Need two stacks
– Operator (e.g. +, /, etc.) stack
– Operand (e.g. 2, a, etc.) stack
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
• 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
Towers Of Hanoi/Brahma
2
1 3
A B C
• 3-disk Towers Of Hanoi/Brahma
Towers Of Hanoi/Brahma
1 2 3
A B C
• 3-disk Towers Of Hanoi/Brahma
Towers Of Hanoi/Brahma
3
1 2
A B C
• 3-disk Towers Of Hanoi/Brahma
Towers Of Hanoi/Brahma
3
2 1
A B C
• 3-disk Towers Of Hanoi/Brahma
Towers Of Hanoi/Brahma
3 2 1
A B C
• 3-disk Towers Of Hanoi/Brahma
Towers Of Hanoi/Brahma
2
3 1
A B C
• 3-disk Towers Of Hanoi/Brahma
Towers Of Hanoi/Brahma
3
2
1
A B C
• 3-disk Towers Of Hanoi/Brahma
• 7 disk moves
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
Recursive Solution
A B C
• move top disk from A to C
Recursive Solution
A B C
• move top n-1 disks from B to C using A
Recursive Solution
A B C
• moves(n) = 0 when n = 0
• moves(n) = 2*moves(n-1) + 1 = 2n-1 when n > 0
Towers Of Hanoi/Brahma
• 2n is BIG
Chess Story
End pin 36 15
=> start 35 16
pin must 34 17
be at top
33 18
of stack.
32 19
31 20
30 29 28 27 26 25 24 23 22 21
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(); …}
Try-Throw-Catch
• When you enter a try block, push the address of
this block on a stack.
• When an exception is thrown, pop the try block
that is at the top of the stack (if the stack is empty,
terminate).
• If the popped try block has no matching catch
block, go back to the preceding step.
• If the popped try block has a matching catch
block, execute the matching catch block.
Rat In A Maze
Rat In A Maze
• Move down.
Rat In A Maze
• Move left.
Rat In A Maze
• Move down.
Rat In A Maze
• Move right.
• Backtrack.
Rat In A Maze
• Move downward.
Rat In A Maze
• Move right.
Rat In A Maze