Fundamental data structure
Algorithm analysis
algorithm and program
- algorithm:described by human languages,flow charts,programming lanuage,pseudocode
- program:written in some programming language(==can be meaningless==)
what to analyze
running time?
==run time==:machine and compiler-dependent
==Time & space complexities==:machine and compiler-independent
Assumption(usually not true)
- sequentially executed
- each instruction is simple,tasks exactlyone time unit
- integer size is fixed & infinite memory
--the average and worst time complexity , as function of input size N
Asympotic Notation
rules
| Function | Name |
|---|---|
| c | Constant |
| Logarithmic | |
| Los-squared | |
| Linear | |
| Log linear | |
| Quadratic | |
| Cubic | |
| Exponential | |
| Factorial |
recursions
1 | long int Fib(int N) /*T(N)*/ |
Compare the algorithm
example
find the largest list
1 | int MaxSubsequenceSum (const int A[], int N) |
1 | int MaxSubsequenceSum ( const int A[], int N ) |
- Divide and Conquer
recursion time complexity
- On-line Algorithm
1 | int MaxSubsequenceSum( const int A[], int N ) |
Logarithm in the running time
find the median
Binary Search
1 | int BinarySearch ( const ElementType A[], ElementType X, int N ) |
Euclid’s algorithm(欧几里得算法)
Find the GCD(Greatest Common Divisor)
1 | function gcd(a, b): |
Exponentiation(快速幂算法)
To compute efficiently
1 | function mod_pow(a, b, m): |
Check your analysis
Lists,Stacks, and Queues
Abstract Data Type(ADT)
A date type that is organized in such a way that the specification on the objects and specification of the operations on the objects are separated from the representation of the objects and the implementaion on the operations.
The List ADT
Operations
- Find the length
- Making an empty
- Find the k-th
- Insert
- Delete
- Find next
- Find previous
implementations
- array
- maxsize has to be estimated
- find_kth takes O(1) time
- insetion and deletion takes O(N) time, involve a lot of data movements
1 | array[i]=item |
- linked list
- find kth takes O(n) time
- insertion and deletion takes O(N) time to find , and O(1) time to change
- cursor implementation of linked list
- requires customized malloc
- Doubly linked circular lists
Multilist
Cursor implementation of linked list
Use the linked list to serve as malloc and free function.
The Stack ADT
fundamental data arrange
Last-In-First-Out -> reverse order
operation
- IsEmpty
- CreatStack
- DisposeStack
- MakeEmpty
- Push
- Top
- Pop
a pop on a empty stack is errror in the stack ADT
Implements
- linked list
- array
1
2
3
4
5struct stack{
int capacity;
int topofstack;
Elementtype *array
}
Application
- balancing symbols
check if parenthesis , brackets , braces are balanced
1 | Algorithm { |
- postfix conversion
Infix to Postfix Conversion
- the order of operands is the same
- operators with higher precedence appear before those with lower precedence
- function calls
1 | void PrintList (List L) { |
The Queue ADT
limited resources
First-In-First-Out
operation
- isempty
- creatqueue
- disposequeue
- makeempty
- enqueue
- front
- dequeue
Implementation
Array
1 | struct QueueRecord { |
Circular Queue
Tree
A tree is a collection of nodes. The collection can be empty;otherwise, a tree consists of
- a distinguished node r,called theroot
- zero or more nonempty (sub)trees ,each of whose roots are connected by a directed edge from r
- degree of a node:number of subtrees of the node
- degree of a tree:the max degree of the nodes of the tree
- parent:a node that has subtrees
- children:the roots of the subtrees of a parent
- siblings:children of the same parent
- leaf:a node with degree 0
- path from to :a (unique) sequence of nodes such that is the parent of
- length of path:number of edges on the path
- depth of :length of the unique path from the root to
- height of :length of the longest path from to a leaf
- height(depth) of a tree:height(root)=depth(deepest leaf)
- ancestors of a node:all the nodes along the path from the node up to the root
- descendants of a node:all the nodes in its subtrees
Implementation
List representation
The size of each node depends on the number of branches.
FirstChild-NextSibling Representation
Binary Tree
A binary tree is a tree in which no node can have more than two children
Expression tree
Tree traversals
1 | Preorder Traversal |
An interative program of inorder traversal
1 | void iter_inorder(tree_ptr tree){ |
Skewed binary tree
Complete binary tress
Properties
- The max number of nodes on level is
- The max number of nodes in a binary tree of depth is
- For any none empty binary tree
Binary Search Trees
A binary search tree is a binary tree.It may be empty.If it is not empty,it satisfies the following properties:
- Every node has a key which is an integer ,and the keys are distinct.
- The keys in a nonempty left subtree must be smaller than the key in the root of the subtree.
- The keys in a nonempty right subtree must be larger than the key in the root of the subtree.
- The left and right subtree are also binary search trees
ADT
Operations
- MakeEmpty
- Find
1 | Position Find(ElementType X, SearchTree T) { |
1 | Position Iter_Find(ElementType X, SearchTree T) { |
- FindMin
1 | Position FindMin(SearchTree T) { |
- FindMax
1 | Position FindMax(SearchTree T) { |
- Insert
- check if the new number is already in the tree
- the last key when search for the key number will be the parent of the new node
1 | SearchTree Insert(ElementType X, SearchTree T) { |
- Delete
- Delete a leaf node:reset its parent link to NULL
- Delete a degree 1 node:replace the node by its single child
- Delete a degree 2 node:
- replace the node by the largest one in its left subtree or the smallest one in its right subtree.
- Delete the replacing node from the subtree
1 | SearchTree Delete(ElementType X, SearchTree T) { |
lazy deletion
add a flag field to each node ,to mark if a node is active or is deleted
- Retrieve
Average-Case Analysis
Place elements in a binary search tree.How high can this tree be?
The height depends on the order of insertion
Priority Queues(Heaps)
Operations
- Initialize
- Insert
- DeleteMin
- FindMin
Simple Implementation
Binary Heap
A binary tree with nodes and height is complete iff its nodes correspond to the node number from 1 to in the perfect binary tree of height
Array representation
Initialize
1 | PriorityQueue Initialize(int MaxElements) { |
Heap Order Property
A min tree is a tree in which the key value in each node is no larger than the key values in its children.
A min heap is a complete binary tree that is also a min tree
Insertion
The only possible position for a new node
1 | void Insert(ElementType X, PriorityQueue H) { |
DeleteMin
1 | ElementType DeleteMin(PriorityQueue H) { |
Other Heap Operations
- Finding any key except min will have to take a linear scan through the entire heap
- DecreaseKey
- IncreaseKey
- Delete
- BuildHeap
Application
Given a list of N elements and a integer K.Find the kth largest element.
d-Heaps
DeleteMin will cost
Disjoint set ADT
Equivalence Relations
A relation R is defined on a set S if for every pair of elements is either true or false.If is true ,then we say that a is related to b
A relation,~, over a set,S,is said to be a equivalence relation over S iff it is symmetric(对称性),reflexive(反身性) and transitive(传递性) over S
Two member x and y of a set S are said to be in the same equivalence class iff
1 | /* Step 1: Read the relations in */ |
Operation
- Union
- Implementation1:
- Implementation2:
- Implementation1:
1 | /* Union by setting the parent pointer of one root to the other root */ |
- Find
- Implementation1:
- Implementation2:
- Implementation1:
1 | /* Find operation */ |
Algorithm using union-find operations
1 | /* Algorithm using union-find operations */ |
Smart Union Algorithm
Union-by-size
always change the smaller tree
N Union and M Find operations takes
Union-by-Height
always change the shallow tree
Path Compression(Union-by-rank)
1 | SetType Find(ElementType X, DisjSet S) { |
Worst Case For
Ackermann’s Function
Graph Algorithms Notes
1. Definitions
Graph where:
- : finite, non-empty set of vertices
- : finite set of edges
Undirected Graph: - Edge
- No self-loops or multi-edges (simple graph)
Directed Graph (Digraph): - Edge
- : tail, : head
Subgraph: - if and
Path: - A sequence of vertices with consecutive edges
- Length: number of edges
- Simple Path: no repeated vertices
- Cycle: simple path with the same start and end vertex
Connected Graph (Undirected) - Every pair of vertices has a path
Component: - A maximal connected subgraph
Tree: - A connected, acyclic graph
Strongly Connected Graph (Directed): - For all , there exists a path and
Degree: - : total number of incident edges
- For digraphs: and
DAG: - Directed Acyclic Graph
2. Graph Representations
a. Adjacency Matrix
Let :
-
if edge exists from to
-
For undirected graphs: symmetric matrix
Time Complexity:
- for traversal
Space Optimization:
- Store only half for undirected: 1D array index
b. Adjacency List
Each vertex stores a list of its adjacent vertices:
-
Space:
-
Time for edge traversal:
c. Inverse Adjacency List (for directed graphs)
- Needed to compute in-degree
d. Multilist
-
Combine forward and backward pointers in one structure
-
Efficient for edge marking and bidirectional operations
e. Weighted Graphs
-
Matrix:
-
List: add weight field to node
3. Topological Sort
Predecessor:
-
is predecessor of if there exists a path
-
Immediate predecessor: edge
Partial Order:
- Transitive and Irreflexive relation
AOV Network:
-
Activity-on-Vertex graph
-
DAG where vertices are activities and edges represent precedence
Definition
A topological order is a linear ordering of the vertices such that for every directed edge , vertex comes before in the ordering.
Algorithm 1: Basic
1 | void Topsort(Graph G) { |
Time Complexity:
Algorithm 2: Using Queue (Improved)
1 | void Topsort(Graph G) { |
Time Complexity:
4. LaTeX Example Snippets
Graph Notation
1 | \[ G = (V, E), \quad V = \{v_1, v_2, \dots, v_n\}, \quad E = \{(v_i, v_j)\} \] |
Degree
1 | \[ \deg(v) = \text{number of incident edges to } v \] |
Topological Sort Condition
1 | \[ \text{For every } \langle i, j \rangle \in E(G), \text{ we have } i \text{ precedes } j \text{ in the ordering} \] |
Note: Topological sort only applies to DAGs. If a cycle exists, the topological ordering is not possible.


























