IE2108 Data Structure and Algorithm Summary
IE2108 Data Structure and Algorithm Summary
IE2108 Data Structure and Algorithm Summary
By EEE Club -
table Content
of
TOPICS PACE
Mathematics 3
↳Basic for Algorithm
↳y Pseudocode 4
3
Algorithm Analysis 5
4. Recursion F
11
6. Binary Tree
8, AVL tree 15
and 1G
9. Merge mergesort
so, Heap and heapsort 18
Partition
11 and quicksort no
search
13.
Binary 22
Tree basics
14) Graph a 29
15, Breadth -
First Search 24
17 Greedy algorithms 28
1) Kruskal's algorithm
is
Prim's algorithm
Tope1: Basic Mathematics
for Algorithm
-
Boolean
(logic) variables: not (), and (1), or (v)
-
Factorial: I = nx (Url),.. x3x4x 1
-binomial efficient/combination:
b
() =
ile!
-Logarithm: = -
logph=Se
->Note: 1g= loga
-Summation:
↑
Ii=1+9+3+. + 4
= 1 2 3 =1+a'+3+..+n= Htel
Ii1+9+5..+h
9
NR
1
=
G
t
za:a +a+... a =
(9-p+1) a
Arithmatic
- series: A an =
a+ (nvld
+ am=ACastan
K= 1
=
. [eactured
n -1
-geometric series: 1) an = a. O
+2 ar = a tart. Had -r
1-R
Telescoping series:
2 Cab -ak: an e
a Mathematical Induction:
Steps:
Basis induction: the statement istrue for
+ of n =
no
- Induction step: -
assume that it's tree
for M = K (k>, n0)
I
prove that it's also true for n =k+1
Algorithm declaration:
Algorithm name
(arg, arg,...
Input: ...
Output: ...
Expressions: =
(Assignment), =
(Equally testing
=
-Selection:
if (condition if (condition
if scondition 23
else
action 8;
-
Iteration:
While loop:
1)
While (condition
action;
action action,
PS: Algorithm Analysis
theoretical analysis of time efficiency
T(n) [(n)
=
Cop =
+ Tn =
running time
#Cop = executive
for a basic operation
(() times basic operation is executed
+) X =
nput size +) = no.
of
-Basic operation: the
operation that contributes most towards the
running time
of
the algorithm.
the rate which the
growth rate:
of the algorithm grows the input size
at cost as
-
grows
A
symptotic analysis
osnotation f (n) =
0(g(ni)
there exists EE and constant Ko such that:
-
If
f(n) 1k.g(n) ((n>, no, nez)
found f(n)
-> g(n) is an
asymptotic upper for
·tote; the possible class and the
use SMALLEST
of functions SIMPLEST expression
aonotation: f(n) =
(g(n)
-
-> gin) is an
asymptotic lower found for f(n)
notation: fn 0(gn1) =
I
f(n) -> (gni) =
->
gin) is an
asymptotic light bound for find
Properties of Asymptotic:
Suppose: fu(n 0(ge(n) = 1 fen =
0(gecn)
-
theorem 3.2; fe(n) +
fe (n= 0(
max(g(n), geen)
-
theorem 3.2:
fu(nx fan = 0
(gn) gecn) x
4) Set up a sun
expressing the number of times the basic operation is executed
the
5, simplify sum to find big-ch of the algo's running
time.
Runtime
analysis
-
4):
running
trie
of
the
algorithm; O(gin)): asymptotic analysis
-
Ratio: T) /g(n)
1) If the ratio
diverges ->
gin is too small
1) If the ratio
converges to 0 -> g(n) is too
big (upper found is not
tight)
the ratio
4) If converges to a cost ->
analysis of algorithm is
probably correct.
#4 Recursion
Definition: Recursion is a
repetitive process in which an algorithm calls
itself
steps to write a Recursive function
1) Determine the input size
Plan
for Analysis of Recursive Algorithms
1. Decide on
parameter n
(indicating input size)
Some examples
Fibonacci sequence:
1)
fibo-a (n)
(n = 0 1) return (n)
if = or v =
=
else (
result (n-c)
=
fibo-2(n-1) +
fibo-2
return result
3
a Factorial function;
fact (n)
if (n =
= 0) return 1,
else return ne
fact (n-1)
#5: Stack, Quene, Linked list
stack
Items
only be added removed from end -> L70; last in, out
-
can one
first
at
nstack
g using Array:
1, stack_mit() S 3, pop(9
8, then throw
t = -1
if empty) EmptyStack Exception
3 elsez=+-1
a empty) ( top 1) 5
4)
S. throw
return t = - L
if empty)) EmptyStackException
=
3 else return St
5, push(vall S
throw FileStack Exception
if(t = = 5.
length-17
else ( += + + h
S1] = ral
3
3
Quene
-
Incention at the near, removal at the
front -> F110: first in, first out
s,
1 =f = -
1 return v
=
= = 1
if (emptyss)
I throw
3 CEmpty Exception
else return alf]
3
4 enquence (all [ 5, dequere() (
if (emptys1) v=
=0 if (empty (1) throw @
Empty exception
=
R + 1 (v = f ) 7 1
1=
if (= =
=
if (v = =
0. size) v = 0 else (
if (v =
=
3 1 (f =
=
G. size) F = 0
GYrT = val 3
3 3
3
preceding new to
I
temp= mode tempprev next,
new =
p P prev =
p.phev
val
temp, data =
next, prev=tempppver,next
p =
p.next
temp.next=p next prnext=temp Y
3
linked list
Implement stack
using
1 stack-mit() a, empty)) ( 3, tops (
top = wull return top == null
if empty)) throw Empty StackException
3 3 else return
top, data
3
4)
pop()( 5, push (rae) (
if (empty (1)
mode
temp= new
throw
Empty StackException temp, data = val
top=top.next top =
temp
return 3
↳
S
linked list
Implement Quere using
squena-mit() a, emptyl) ( 3, front)
f = will return
f = will
=
will (v will
temp, next:
if = =
=
) r= f
=
S
if Sempty (1) v=
f =
temp else
else3r.next =
temp f f = next
v= temp 3
3 9
3 S
#pic6: Binary Tree
-
A rooted tree in which each node has 0 or 1 or 2 children
Preorder traversal ⑭
2
Goto
(root)
preorder
if
(root! = nules 3
visit roof;
preorder (root.left),
preorder (root, right),
Preorder: BDCEG H
3
*
->
In order traversal
inorder (root) 3
(
if (root? nuel)
=
postorder (root,
right);
visit (root) ;
-> Postorder: DBG HEC A
3
3
Search Tree
TpcT: Binary
Definition
A node's left child must have
a data - its
parent
② ⑧
E
-
-A mode's
light child must have a datax its parent
BST insertion
5
-
cases:
1. Insert to an
empty tree
Insert to left
a a
non-empty tree, subtree
empty
3. Insert to a
non-empty tree, right subtree
empty
Insert to left
4 a
non-empty tree, subtree
non-empty
5. Insert to a
non-empty tree, right subtree
non-empty
BSTinsert (root, wall ( BsTwisest -
recurs (root, temps [
1) set up mode to be added to the tree if (temp-data 1 rootdata) (
11 case 1:
else BsTwisert - recurs
(root-left, tempe
empty tree
3
if (root == mll) return temp;
else? Igoes to
else? Ifor all other cases
right
if (root, null)
BSTinsert -
recurs (root, temp);
right ==
9
root,
right temp;//case 4
=
3 lcase 5
return roof,
3
else BsTinsertrecurs (root,
right, temp),
3
3
BST deletion
a
BSTreplace (root, ref): for the ease
ref has 0 or 1 child.
If ref
is root, set let's child as the root, stop
if(ref==rout) >//delete
root
3
o
Ptogether Deletion algorithm
-
When the mode "ref" to be deleted has a children
1, Locate the node "suce" containing the min data in ref's right subtree,
sace must have no left child
"succ"
2, replace the value
of "ref" by the value
of
11 right
if (reg.left == will
reg. == nule)
succ=ref.right
white (succ. succ.left
left will) snce =
I thus
move such to
ref, deleting ref
I) delete succ
3
#8: ALL tree
the
-Height of a tree number
of edges
on
longest path from the root to a
leaf
An
↳
1, a tree with a
single node has
height o
ArL balanced: if the difference in the heights between the left and
right sub-trees
-
of
mode is at most 1
any
the lowest
-
When
maintaining balance, we
only need to
six the imbalance at mode.
lase left-left
case
left-Right
Case
Right-Right &
Right-left
Re: Merge &
Mergesort
Merge Merge a sorted
arrays (non-decreasing order)
(K =1 to a)
for ([K]=Alp-k+1] /copy sub-array A(p...9) to (
1:1, j =1, R=
P
While (i 1a and
jeb) [ /copy of
remainder
Ar]= (9i]; i = i+ ↓
it
i = 8, & = 4 + 1
3 3
else (
While (j 2b) [
ACr] =
R9j],
Al] = R3j]
j=j+1,
j=jt]-
3
& = 1+ 1
1= 1 + 1;
3
3
Mergesort Divide and
conquer paradigm
the has single element, stop
1. If array
be sorted
2, Divide the
array
to into a
nearly equal parts
3. Conquer: each
part is sorted
using mergesort
4, The two sorted then into 1 corted
subarrays are
merged array.
mergesort (A, 1, 3) 3
I) is element, just
only I return
if (i = =
j) return
1) divide A into a
nearly equal parts
m =
(itj) /G
mergecort (A, i, m)
merge
(A, i, m, j,
Complexity
T(n) = number
of operations needed
for an input array of size n
Merge:
-> Tn =
T(E) + 0(n)
(n) O(nign)
=
->
#CO Heap Heapsort
Heap structure:
to a
point (there's at most I mode with no
ribling)
Miheap value children
of each mode I value its
of
· Mheap: value of each mode is value
of
its children
Represent a
heap using an
array
-Node number I has
parent number (1); legtchild: 25% right child Gxi+1
Maintaining a
heap: Siftdown child
1) Find
larger
until:
2) Repeatedly swap
+
Node has no child, or
orimplementation: oi ve implementation?
Making a
Maxheap-Heapify
Idea: the leaves
-
0 (n)
->
Complexity:
Delete a mode
from a
maxheap
a Delete roof;
- - alany
node:
Heaport
#C11: Partition & Quicksort
partition
-
Divides an
array
into a
parts, sizes
of
the 2 can be
nearly equal - highly unequal
- Pivot/Partition element: the division depends on this particular element
algorithm:
<Par
-Partitions the
array Adi..] by inserting val = Alr] at the index where it
- Idea:
1) Scan
from left for element smaller than val = AliT
Hul
Increase h
unmatn
1) (make room
for smaller)
+) Exchange
+) Repeat until the last element of the array
Alp...R] into 2
mbarrays Alp...hr] and
2. Conquer
-
sort the
sub-arrays by recursive calls to quick sort,
the
them -> entire
array Ap..r] is now sorted.
outperformance:
-Worst case: ECM) -> horse than heapsont & mergesort if the array is sorted
-Average case: 8
ntogn
Tola: Comparisons of Corting Algorithms
Order Statistics
Comparisons of Sorting Algorithms
3
-> a
symptotically optimal: cannot
do better
-
Comparison sorts:
comparisons between two elements to output a sorted
sequence.
-
theorem
any comparison
sort algorithm requires -
(ntogn) comparisons
in the worst case.
element with
-order statistics: queries that ask
for an a
given rank.
th
-the K order statistic set in elements is its 4th smallest element
of
Median: the element such that other
-
half of the elements are smaller and e
the
remaining half are
larger.
asproblem: find the kit
smallest element in A
an
array
-> Use partition, no need to sort the entire
array
Complexity: O(nY)
Search
Tip Binary 13;
simplest one-by-one
0(n)
-complexity:
Steps:
-
t Compute the
midpoint K = ()
solved!
1 If LCK] =
key-> problem
+) Otherwise, divide the
given array
into a
parts of nearly equal size:
.,
↳
If key
< LTK] = search
for key in
Array s
19k> search
↳ If key] => for key in
Array I
- tie
complexity: OClogn)
#14: Graphs & Tree basics
graphs
-Subgraph:G= (VE') is a
subgraph of
G =
(VE) if VCV and E'CE
Connectivity; a
graph is connected if there's
a
path joining every pair of distinct vertices.
tree
that contains
-
Every tree at
theorem: least)
->
Every connected graph possesses (at I
spanning tree.
pigraph
T15: Breadth - First Search
Basic idea
Expand the
frontier between discovered and undiscovered vertices
uniformly across
are
explored.
Quere Implementation Breadth-First-Search (G.s)
1) Add s to a
queue a
while not
2, a
is
empty:
i) Return the value and call it
front of a v
MI
1) initialize array "visit"
in
already 9
U=
of vertices; edges
+ no, m = no.
of
↑16: Depth - First Search
Basic idea
-
search
deeper in the graph whenever possible
-
When a
leaf mode is
reached, backtrack: explore the most
recently visited
vertex that still has unvisited neighbors, then visit that unvisited
neighbor.
-
Continue the process until all reachable vertices from the start vertex are visited
2, while I is not
empty:
Return the value s, call it
i) top of
o
has
ii)
If w one unvisited adjacent vertex u, push a tos, add u to visit
of
the shortest
o ecties, find
route that visits
possible every city exactly
the
once and return to
starting city
solution: The neighbor solution
Any nearest -
-
In each step, travel to the
city with the min distance
from the current
city
the next the start has (n1) choices
-
solution:
Anal exhaustive search
using
The total number of (n-1)!
-
possible wites is
Tip
18: The shortest path problem
the shortest
path problem
-given a
weighted graph and 2 vertices u and v, he want to find a
path from
u too with the minimum total
weight.
↳ theorem: a
sub-path of the shortest path is itself a shortest path.
-shortest path tree
formed by the shortest paths from a start vertex to all
spanning tree
of a
weighted graph minimum
->
Different from the shortest path tree.
Kruskal's Algorithm
Prim's Algorithm