4 Creating Adjacency Lists
An undirected graph is represented by the sets and . If these sets are maintained as simple lists where the buffer communicates with the vertex list and communicates with the edge list, Algorithm 1 creates an adjacency list for .
first() |
while |
insert() |
next() |
first() |
while |
insert() |
insert() |
next() |
The first loop in Algorithm 1 creates a header for each vertex. This operation is not strictly necessary given the current data definition; however, it is often required in practical implementations.
You should observe that the algorithm inserts each edge in into the adjacency list twice: once in the stated direction and once in the reverse direction. If is a directed graph, the reverse insertion is inappropriate (i.e. omit the final insert statement in Algorithm 1). It should be apparent that the algorithm has a time complexity of if all operators have time complexity of .
It is often beneficial to create an adjacency list based on an alternate labeling of the vertices of . This operation requires a mapping of the integers from 1 to onto the set . Algorithm 2 maps to the order in which it is enumerated.
first() |
while |
map() |
next() |
Algorithm 3 combines these two procedures. It labels according to its order of enumeration and creates an adjacency list based on this labeling.
first() |
while |
map() |
insert() |
next() |
= first() |
while |
evaluate() |
evaluate() |
insert() |
insert() |
next() |
If map and evaluate have constant time complexity, the overall algorithm retains its linear complexity.
Note. In a practical implementation, map will insert the pair into a data structure that is optimized for searching and evaluate will look up in this data structure. Efficient operations of this sort have a time complexity of . Therefore, adjacency list creation will have complexity .