Professional Documents
Culture Documents
1. Array
a[1] a[2] a[3] a[n]
10
3. Binary Tree 6 9
4 7 17 20
1 4 13
9
Fundamental Abstract Data Structures
1. Stack
an
• Operations a stack supports: last-in-first-out (pop, push)
front rear
1. Graph
• Operations a graph support: finding neighbors
• Implementation: using list or matrix
G (V , E )
V (a, b, c, d , e, f )
E {(a, c ), (b, c ), (d , a), (c, e), (e, c), (b, f ), (d , e), (e, f )}
a b c d e f
a c a 0 0 1 0 0 0
a c b c f
b b 0 0 1 0 0 1
c e
c 0 0 0 0 1 0
d e f d a e d1 0 0 0 1 0
e f c
e 0 0 1 0 0 1
f
f 0 0 0 0 0 0
Adjacent lists
Adjacent matrix
2. Binary Search Tree
Definition 1 Binary Search Tree is a Binary Tree
satisfying the following condition:
(1) Each vertex contains an item called as key 15
which belongs to a total ordering set and two 6 18
links to its left child and right child,
respectively. 3 7 17 20
(2) In each node, its key is larger than the keys of 1 4 13
all vertices in its left subtree and smaller than
the keys of all the vertices in its right subtree. 9
Operations a binary search tree support: search, insert, and delete an element
with a given key.
1. Linear search
int lsearch(int a[], int v, int l, int r)
{
for (int i=l; i<=n; i++)
if (v==a[i]) return i;
return -1;
}
2. Binary search
int bsearch(int a[], int v, int l, int n)
{
while (r>=l)
{int m=(l+r)/2;
if (v==a[m]) return m;
if (v<a[m]) r=m-1; else l=m+1;
}
return -1;
}
Complexity of Algorithms
Using silicon computer, no matter how fast CPU will be you can
never solve the problem whose running time is exponential !!!
Asymptotic Notations: O-notation
c0 g ( n )
t (n)
n
n0
t ( n)
If lim n c (c 0 is a constant ) , then t(n) O(g(n)).
g ( n)
Example 3 Prove 2n+1=O(n)
Example 5
List the following function in O-notation in increasing order:
lg n, n, n 2 , n lg n, n 3 , n!,2 n.
Factorial Algorithm
Procedure factorial(n) Algorithm factorial calls itself
if n = 0 return 1 in its body!
=n
Example 12 Solve the recurrence Example13 Solve the recurrence
T (n) T (n 1) n n 1 T (n) T (n / 2) 1 n 1
T1 1 T (1) 1
T (n) T (n 1) n (Assume that n is a power of 2.
T (n 2) (n 1) n That is, n 2 k , where k log n).
T (n 3) (n 2) (n 1) n T (n) T (n / 2) 1
...... T (n / 2 2 ) 1 1
T 12 3 ... (n 2) (n 1) n T (n / 23 ) 1 1 1
1 2 3 ... n ......
n(n 1) / 2 T (n / 2i ) i
......
T (n / 2 k ) k (k log n)
1 log n