You are on page 1of 40

Graphs And Heaps

Objective:
To introduce the properties of a graph and
heap
To explain the graph traversal and basic
algorithm
To explain the heap basic algorithm
1
GRAPH

2
Graph Definition

 A graph is a collection of nodes, called vertices, and a


collection of segments, called lines, connecting pairs of
vertices.
 A graph consist a set of vertices and a set of lines.

vertices

A B

lines

Struktur Data & Algoritma


Types of graph

Graphs may be either directed(digraph) or undirected graph.

Directed Graph (Digraph) Undirected Graph


Each line has a direction (arrow No direction (arrow head) on any
head) of the lines
Lines known as arcs Lines known as edges
The flow for the directed graph can The flow for undirected graph
follow only the indicated direction. between two vertices can go in
either direction.

Struktur Data & Algoritma


Directed and Undirected graph

A and B are adjacent

Figure 12-1 D and F are not adjacent

Two vertices in a graph are said to be adjacent vertices(or neighbors)


if an edge directly connected to them.

Struktur Data & Algoritma


Path of the graph

 A path is a sequence of vertices in which


each vertex is adjacent to the next one.
 From the previous slide, {A,B,C,D} is one
path and {A, B, E, F} is another.
 In the undirected graph, you can travel in
either direction.

Struktur Data & Algoritma


 A cycle is a path consisting at least three vertices that start and end
with the same vertex.
 Diagram (b) below shows B,C,D, E ,B is a cycle.
 however in diagram (a) do not constitute a cycle because in a digraph

Struktur Data & Algoritma


 Two vertices are said to be connected if
there is a path between them. Directed graph
is a strongly connected if there is a path
from each vertex to every vertex in the
digraph.
 A digraph is weakly connected if at least two
vertices are not connected.
 A graph is disjoint if it is not connected.

Struktur Data & Algoritma


Strongly, weakly connected and
disjoint graph

Struktur Data & Algoritma


 The degree of a vertex is the numberof lines
incident to it.
 The degree for vertex B in diagram below is
3 and the degree for vertex E is 4.

Struktur Data & Algoritma


 The outdegree of a
vertex in a digraph is the
number of arcs leaving
the vertex.
– The outdegree for vertex
B is 2
 However the indegree is
the number of arcs
entering the vertex.
– The indegree for the
vertex B below is 1

Struktur Data & Algoritma


Graph traversal

 There will be one application that requires that all


vertices in a given graph be visited.
 In traversing the graph one must ensure that each
vertex is visited only once.
 Problem arises when one vertex have multiple paths
to it. thus to ensure the vertex is visited once, flag is
place at each vertex that has been process.
 two standard graph traversal are
– Depth first
– breadth first

Struktur Data & Algoritma


Depth First Traversal

 In depth first traversal, all of a node’s


descendents are processed before moving to
an adjacent node
 It is the same as the preorder traversal in
tree A

B C D

E F H G I

Depth first travel [ A B E F C D H G I ]


Struktur Data & Algoritma
Depth First Traversal –
Undirected graph
A
Dept first traversal
AXHPEYMJG
X H Y

E
G P M J

P Y
H E E M M J
A X G G G G G G G

Struktur Data & Algoritma


Depth First Traversal –
Directed graph

Dept first traversal


ABCDEFHIG

Struktur Data & Algoritma


Depth-First Traversal Algoritm
Algorithm deleteFirst (val graph <metadata>)
Process the keys of the graph in depth-first order.
Pre graph is a pointer to a graph head structure
Post vertices “processes”

1. if (empty graph)
1.1 return
2. walkPtr = graph.first
3. loop (walkPtr)
3.1 walkPtr->processed = 0
3.2 walkPtr = walkPtr->nextVertex
4. end loop
5. createStack (stack)
6. walkPtr = graph.first
7. loop (walkPtr not null)
7.1 if (walkPtr->processed < 2)
7.1.1 if (walkPtr->processed < 1)
7.1.1.1 pushStack (stack, walkPtr)
7.1.1.2 walkPtr->processed = 1
7.1.2 end if
Struktur Data & Algoritma
Cont.
7.1.3 loop (not emptyStack(stack))
7.1.3.1 popStack (stack, vertexPtr)
7.1.3.2 process (vertexPtr->dataPtr)
7.1.3.3 vertexPtr->processed = 2
7.1.3.4 arcWalkPtr = vertexPtr->arc
7.1.3.5 loop (arcWalkPtr not null)
i. vertToPtr = arcWalkPtr->destination
ii. if (vertToPtr->processed is 0)
a. pushStack (stack, vertToPtr)
b. vertToPtr->processed = 1
iii. end if
iv. arcWalkPtr = arcWalkPtr->nextArc
7.1.3.6 end loop
7.1.4 end loop
7.2 end if
7.3 walkPtr = walkPtr->nextVertex
8. end loop
9. destroyStack (stack)
10. return

End depthFirst
Struktur Data & Algoritma
Breadth First Traversal

 In breadth first traversal, all adjacent vertices


of a vertex are processed before moving to
the next level

B C D

E F H G I

Breadth first travel [ A B C D E F H G I ]

Struktur Data & Algoritma


Breadth First Traversal –
Undirected graph

A Breadth first traversal


AXGHPEMYJ
X H Y

E
G P M J

A X GH HP PE E MY YJ J

Struktur Data & Algoritma


Breadth First Traversal –
Directed graph

Breadth first traversal


ABCEDFHIG

Struktur Data & Algoritma


Breadth First Traversal Algorithm
Algorithm breadthFirst (val graph <metadata>)
Process the keys of the graph in breadth-first order.
Pre graph is a pointer to a graph head structure
Post vertices processed

1. if (empty graph)
1.1 return
2. end if
3. createQueue (queue)
4. walkPtr = graph.first
5. loop (walkPtr not null)
5.1 walkPtr->processed = 0
5.2 walkPtr = walkPtr->nextVertex
6. end loop
7. walkPtr = graph.first
8. loop (walkPtr not null)
8.1 if (walkPtr->processed < 2)
8.1.1 if (walkPtr->processed < 1)
i. enqueue (queue, walkPtr)
ii. walkPtr->processed = 1
8.1.2 end if
Struktur Data & Algoritma
Cont……
8.1.3 loop (not emptyQueue (queue))
i. dequeue (queue, vertexPtr)
ii. process (vertexPtr)
iii. vertexPtr->processed = 2
iv. arcPtr = vertexPtr->arc
v. loop (arcPtr not null)
a. toPtr = arcPtr->destination
b. if (toPtr->processed zero)
1. enqueue (queue, toPtr)
2. toPtr->processed = 1
c. end if
d. arcPtr = arcPtr->nextArc
vi. end loop
8.1.4 end loop
8.2 end if
8.3 walkPtr = walkPtr->nextVertex
9. end loop
10. destroyQueue (queue)
11. return

End breadthFirst
Struktur Data & Algoritma
Graph operation

 Graph operation includes:-


– Add a vertex
– Delete a vertex
– Add an edge
– Delete an edge

Struktur Data & Algoritma


Add Vertex

 Add vertex inserts a new vertex into a graph.


When a vertex is added. It is disjoint. Add
vertex is just the first step in a insertion
process.

Struktur Data & Algoritma


Add edge

 Add edge connects a vertex to a destination vertex.


If a vertex requires multiple edges, then add an edge
must be called once for each adjacent vertex.
 To add an edge, two vertex must be specified. If the
graph is a digraph, then one must be specified as the
source and one as the destination.

Struktur Data & Algoritma


Delete vertex

 Removes a vertex from the digraph.

Struktur Data & Algoritma


Delete edge

 Delete edge removes one edge from a graph

Struktur Data & Algoritma


HEAPS

28
What is heap ?

 A binary heap is a complete binary tree


which satisfies the heap ordering property.
The ordering can be one of two types:
– Minimum heap (min-heap)
– Maximum heap (max-heap)

Struktur Data & Algoritma


Heap
min-heap max-heap

the min-heap property: the value the max-heap property: the value
of each node is greater than or of each node is less than or equal
equal to the value of its parent, to the value of its parent, with the
with the minimum-value element maximum-value element at the
at the root. root.

Struktur Data & Algoritma


Heap Data structure
 We could implement heaps
using a linked list like
structure, like we did with
binary trees but in this 0
instance it is actually easier
to implement heaps using 2
1
arrays.
 We simply number the
nodes in the heap from top 4 5 6
3
to bottom, numbering the
nodes on each level from
left to right and store the ith
node in the ith location of
the array. (in C++ index start
from zero).

Struktur Data & Algoritma


Heap data structure
 An array A that represents a heap is an array with two attributes
– length, the number of elements in the array
– heap-size, the number of heap elements stored in the array
 Viewed as a binary tree and as an array :

1 2
4 5 6
3

7 8
9
If node x is in location i
left_child(x) -------------> 2i + 1
0 1 2 3 4 5 6 7 8 9 right_child(x) -----------> 2i + 2
parent(x) ----------------> [(i -1)/ 2]

Struktur Data & Algoritma


Basic Heap algorithm

 One of the more basic heap operations is


converting a complete binary tree to a heap.
 The basic algorithm in converting a complete
binary tree to a heap are:-
– ReheapUp
– ReheapDown

Struktur Data & Algoritma


ReheapUp

 Repairs a “broken” heap by floating the last


element up the tree until it is in its correct
location in the heap.
 The tree below is not a heap due to the node
25.it not fulfilling the max-heap properties
42
21 32

16 12 20 30

13 15 10 25
Struktur Data & Algoritma
ReheapUp
42
21 32
Last element (25)
Moved up
16 25 20 30

13 15 10 12

42
25 32 Moved up again
Tree now is a heap
16 21 20 30

13 15 10 12

Struktur Data & Algoritma


ReheapUp Algorithm
Algorithm reheapUp (ref heap <array>, Val newNode <index>)
Reestablishes heap by moving data in child up to its correct location in
the heap array
Pre heap is array containing an invalid heap
newNode is index location to new data in heap
Post heap is been reodered
1. if(newNode not zero)
1. Parent = (newNode-1)/2
2. If (heap[newNode].key>heap[parent].key)
1. Swap (heap, newNode, parent)
2. reheapUp (heap, parent)
3. End if
2. end if
3. Return
end reheapUp

Struktur Data & Algoritma


ReheapDown

 Repairs a broken heap by pushing the root


down the tree until it is in its correct position
in the heap
 The tree below is not a heap due to the node
10.it not fulfilling the min-heap properties
10
3 2

17 19 36 7

25 70
Struktur Data & Algoritma
2
3 10 Root moved down
(right)
17 19 36 7

25 70

2
3 7
Moved down again
Tree now is a heap
17 19 36 10

25 70

Struktur Data & Algoritma


ReheapDown Algorithm
Algorithm reheapUp (ref heap <array>, Val root <index>, Val last<index>)
Reestablishes heap by moving data in root down to its correct location in the heap array
Pre heap is an array of data
root is root of heap or subheap
last is an index to the last element in heap
Post heap has been restored
Determine which child has larger key
1. If ( root * 2 + 1 <= last )
there is at least one child
1. leftKey = heap [ root * 2 + 1 ].data.key
2. If ( root * 2 + 2 <= last )
1. rightKey = heap[ root * 2 + 2].data.key
3. else
1. rightKey =lowKey
4. End if
5. If ( leftKey > rightKey)
1. largeChildKey = leftKey
2. largeChildIndex = root * 2 + 1
6. Else
1. largeChildKey = rightKey
2. largeChildIndex = root * 2 2
7. end if
Test if root > larger subtree
8. If ( heap[root].data.key < largeChildKey)
1. Swap ( heap, root, largeChildIndex)
2. reheapDown ( heap, largeChildIndex, last )
9. end if
2. End if
3. Return
end reheapDown
Struktur Data & Algoritma
Heap Application

Heaps are favorite data structures for many applications.


 Heapsort: One of the best sorting methods being in-place and
with no quadratic worst case scenarios.
 Selection algorithms: Finding the min, max or both of them,
median or even any k-th element in sublinear time can be done
dynamically with heaps.
 The Heap Data Structure is an efficient structure for
implementing a simple priority queue. For jobs that require that
we process records with keys/priorities in order, but not
necessarily in full sorted order such as:-
– Simulation Systems, where events need to be processed
chronologically.
– Job scheduling in computer systems.

Struktur Data & Algoritma

You might also like