Mix-and-Match

advertisement
CS1020 Data Structures and Algorithms I
Lecture Note #17
Mix-and-Match
Data Structures with
Multiple Organisation
Basic Data Structures



Arrays
Linked Lists
Trees (to be covered in CS2010)
We can combine them to implement
different data structures for different
applications.
[CS1020 Lecture 17: Mix-and-Match]
2
Mix-and-Match

Array of Linked Lists


E.g.: Adjacent list for representing graph
E.g.: Hash table with separate chaining
1
2
3
[CS1020 Lecture 17: Mix-and-Match]
3
Adjacency List for Directed Graph
1
2
2
4
3
2
v1
3
v3
4
4
5
v2
4
v5
v4
G
[CS1020 Lecture 17: Mix-and-Match]
4
Adjacency Matrix for Directed Graph
Matrix[i][j] = 1 if (vi, vj)E
0 if (vi, vj)E
1
2
3
4
5
v1
v2
v3
v4
v5
1
v1
0
0
0
0
0
2
v2
1
0
1
0
0
3
v3
0
0
0
0
1
[CS1020 Lecture 17: Mix-and-Match]
4
v4
0
1
1
0
1
5
v5
0
0
0
0
0
v2
v1
v3
v5
v4
G
5
CS1102 AY2003
[CS1020 Lecture 17: Mix-and-Match]
6
CS1102 AY2003: Use Adjacency Matrix
Operation
Big-O
insert(i, j)
O(1)
1
delete(i, j)
O(1)
2 T
exists(i, j)
O(1)
3
neighbours(i)
O(n)
4 T
[CS1020 Lecture 17: Mix-and-Match]
1
2
T
3
4
T
T
7
CS1102 AY2003: Use Adjacency List
Operation
Big-O
insert(i, j)
O(1)
1
2
3
delete(i, j)
O(n)
exists(i, j)
O(n)
neighbours(i)
O(ni)
[CS1020 Lecture 17: Mix-and-Match]
4
8
Problem

Searching on an unsorted linked list is O(n)

How to improve it to O(1)?
Use hashing.
(i, j) as key and the hash value returned by hash
function to be index to a hash table where (i, j) is
stored together with the reference to the node in
the linked list.
[CS1020 Lecture 17: Mix-and-Match]
9
Use Adjacency List
Operation
Big-O
insert(i, j)
O(1)
1
2
3
delete(i, j)
O(n)
exists(i, j)
O(1)
neighbours(i)
[CS1020 Lecture 17: Mix-and-Match]
O(ni)
4
Is delete (i, j)
O(1)?
10
CS1102 AY2003
Build an adjacency list of the graph, where the lists are
doubly linked.
Build a hash table with (i, j) as key, and a reference to the
node representing (i, j) in the adjacency list as value.
[CS1020 Lecture 17: Mix-and-Match]
11
End of file
Download