TDT4120: Algorithms and Data Structures
Are you looking for an overview of all runtimes, you will find them all at the bottom, Runtimes for Curriculum Algorithms.
What are algorithms?
An informal definition: An algorithm is any clearly defined method for calculations that can take a value (or a set of values) as input and return a value (or a set of values) as output.
One can also view it as a tool that can solve a defined calculation problem. When defining the problem, one has to describe which relationship is desired between input and output, for example: «Input: A city road map and two points. Output: The shortest path (measured in meters) between the tho points.»
Description of solution: There is no general standard for describing an algorithm. You can describe it with natural language, pseudo code, as code or through hardware drawings. The only requirement is that the description is precise.
Instances: Each collection of inputvalues to a problem is called an instance. For example can an instance of the problem above have input values such as a road map of Trondheim, and the two points are the geographic coordinates of NTNU Gløshaugen og NTNU Dragvoll.
True or False?: An algorithm can either be true or false. If an algorthim is true, it will for all possible instances defined give the correct output; for example it is only to be expected that a sorting problem will not have problems sorting all possible collections of positibe whole numbers. If it is false, this will not be the case. F.ex: you may have invented an algorithm that solves all sorting problems by returning the list in reverse. This will only in some instances return the correct output, but only for a subset of potential instances.
Basic Datastructures
This course covers several different datastructures with respect to various problems. It is therefore important to have a general overview of the most important ones.
Linked lists
Singly linked list (Public Domain, Lindisi)
A linked list is a basic linear structure that represents elements in sequence. The concept behind the structure is that the sequence of elements is conserved by each element pointing to the next in the sequence (se the figure above). Explained in code:
class Node:
def __init__(self):
self.value = None
self.next = None
n1 = Node()
n2 = Node()
n3 = Node()
n1.value = 1
n2.value = 2
n3.value = 3
n1.next = n2
n2.next = n3
With the code above the structure will be n1 > n2 > n3
We can also have double linked lists, where each node contains a value and a pointer both to the previous and next nodes.
Runtimes
Action  Runtime 
Insert at the start  O(1) 
Insert at the end  O(n) 
LookUp  O(n) 
Delete element  lookUp + O(1) 
Abstract Datastructures
Queue
A queue is an abstract datastructure that preserves the elements sequence and has two operations, enqueue and dequeue. Enqueue is the insert function, which inserts elements at the back of the queue. Dequeue is the exctraction function, and retrieves the first element at the front of the queue. A queue is therefore a FIFOdatastructure (First In First Out).
Stack
A stack is an abstract datastructure which, similar to a queue, preserves the elements sequence. Unlike a queue however, a stack is LIFO (last in first out) implying that it both inserts and extracts elements from the back of the structure. These operations are called push and pop respectively.
Heap
A heap is a list which can be viewed as a binary tree. A heap is an implementation of the priority tree datastructure. Check out heapsort
Max heap property: No node can have a higher value than its parent node.
Hash
 similar to bucket sorting.
 collisions can occur as more than one object is put into a bucket
Let n be the number of keys, and m be the length of the hash array. With uniform hashing the keys are distributed evenly across the m cells.
The load +alpha = n/m
Method: 1) Solve with linked list, at the risk of getting very long lists. 2) Solve with "open addressing", and when the bucket is full it overflows to next bucket.
Hash functions:
Division method h(k) = k mod m where m a prime number far from the power of 2.
Multiplication method: h(k) = floor(m((kA)mod 1)) where 0<A<1
Key terms: linear probing, quadratic probing and perfect hashing (for the hard core)
Runtimes( assuming single, uniform hashing and chaining):
Function  Best Case  Average Case  Worst Case 
Failed Search  
x  
y 
Runtime Calculations
Runtime is a measurement of how effective an algorithm is and is by far th emost important measurement in this course.
About Runtimes
Why Do We Need Runtimes?: In a world where computers are inifitively fast and you had infinite storage space, any true algorithm could be used to solve a problem  no matter how badly desgned it was. However, reality is different and therefore runtime is important.
Runtimes Explained: A runtime describes the relationship between the size of the problem measured in input size and how long time it takes to solve it. It is possible to consider the following: The runtime will tell you that if you have a problem of a certain size, it will take so much more time if you i) insert one more element to the input or ii) double the size etc. Naturally this growth is desired to be as low as possible.
Some Common Runtimes
The most general and used runtimes sorted from high to low.
Complexity  Name  Type 
Factorial  General  
Exponential  General  
Polynomial  General  
Cubic  Polynomial  
Quadratic  Polynomial  
Loglinear  Combination of linear and Polynomial  
Linear  General  
Logarithmic  General  
Constant  General 
Recursion
Recursion is a problemsolving method which is based on the fact that a solution to a problem consists of the solutions to smaller instances of the same problem. This technique will be a recurring theme in several of the algorithms in the curriculum.
One of the most common examples of recurisivity is the Fibonacci sequence, defined as:
Fibonacci numbers
Good examples of recursive algorithms are Merge, Quick Sort and Binary search. We also find recursive solutions through dynamic programming.
The Master Theorem
The Master Theorem is a recipe solution for finding the runtime of several reccurences.
.
This type of recurrence often occurs together with divideandconquer algorithms such as Merge sort.
The problem is split up into
If we didn't already know the runtime for Merge sort, we can quickly discover it by solving this recurrence. Solving the recurrence could also be achieved by using the Master Theorem as follows:
 Identify
$a, b, f(n)$  Calculate
$\log_b a$  Consult the following table
Table over three potential outcomes of the Master Theorem:
Case  Requirement  Solution 
1  
2  
3 
Returning to the merge sort example. We have found
Example
Another example retrieved from the 2009 Continuation Exam:
Solve the following recurrence. Give the answer in asymptotic notation. Give a short explanation.
We have
Sorting and Search
Sorting and search are two problems that either occur as stand alone problems or as a subproblem. Sorting implies organizing a set of elements into a specific order. Searching implies that we are looking to find a certain element in a set of elements.
Search
Finding a specific element in a datastructure is a common problem. In a list of numbers we can search for the median, or a certain number. In a graf we may want to search for a way to get from one element to another. Searching algorithms for graphs (DFS and BFS) can be found under Graphalgorithms.
To search in lists we have two primary methods: Brute Force and Binary Search.
Brute Force
This method is pretty self explanatory. Iterate through the list (sorted or unsorted) from beginning to end and compare each element with the element you are trying to find. With
Binary Search
If we know that the list we are searching is sorted, we can use a different strategy. Given we are searching for value
In Python:
def binary_search(li, value, start=0):
# Dersom lista er tom, kan vi ikke finne elementet
if not li:
return 1
middle = len(li) // 2
middle_value = li[middle]
if value == middle_value:
return start + middle
elif value < middle_value:
# Første halvdel
return binary_search(li[:middle], value, start)
elif value > middle_value:
# Siste halvdel
return binary_search(li[middle + 1:], value, start + middle + 1)
Since we can ignore substantial parts of the list for each choice, the resulting run time is:
Best Case  Average Case  Worst Case 
Sorting
Sorting algorithms can be categorized into two groups: Comparison based and distributed/noncomparisonbased.
Stability
A sorting algorithm can be considered stable if the order of identical elements in the list that is to be sorted is preserved throughout the algorithm. Given the following list:
Sorting it with a stable algorithm the identical elements will stay in the same order before and after the sort.
Comparison Based Sorting Algorithms
All sorting algorithms that are based on comparing two elements to determine which of the two are to come first in a sequence, are considered comparison based. It is proven that
Merge sort
Merge sort is a comparison based sorting algorithm It is also an example of a divide and conquer algorthim.
Best Case  Average Case  Worst Case 
The core aspects of the algorthim is as follows:
 Divide the unsorted list into
$n$ sublists which each contain one element (a list with only one element is sorted)  Pairwise, merge together each sorted sublist.
For all practical purposes this is implemented recursively. The function takes one parameter, the list that is to be sorted. If the list contains only one element, we return this list since it is already "sorted". If it is longer, we divide it up into two equal sublists (odd numbered lists get one larger than the other) and a recursive merge sortcall is made on each sublist. The returnvalues from each recursive call is then merged together. In Python:
def merge_sort(li):
if len(li) < 2: # Dersom vi har en liste med ett element, returner listen, da den er sortert
return li
sorted_l = merge_sort(li[:len(li)//2])
sorted_r = merge_sort(li[len(li)//2:])
return merge(sorted_l, sorted_r)
def merge(left, right):
res = []
while len(left) > 0 or len(right) > 0:
if len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
elif len(left) > 0:
res.append(left.pop(0))
elif len(right) > 0:
res.append(right.pop(0))
return res
The merge function runs in linear time. To analyze the runtime to Merge sort we can set up the following recurrence:
In other words it will take twice as long to sort a list of length
Most implementations of Merge Sort are stable. As a result of the algorithm continuously producing new sublists, it requires
Quicksort
Quicksort is a comparison based sorting algorithm that also uses divide and conquer tactics.
Best Case  Average Case  Worst Case 
Similar to Merge Sort, Quicksort divides the problem into smaller parts and then recursivesly solves. The quicksort function takes one parameter, the list that is to be sorted. The concept is as follows:
 Only one element in the list? In this case the list is sorted and is to be returned.
 Select a pivot element, the easiest being the first element in the list.
 Create two lists, one (lo) which contains the elements from the original list that are smaller than the pivot element, and (hi) that contains all elements larger than the pivot.
 Recursively sort lo and hi with Quicksort, returning: lo + pivot + hi
In Python:
def quicksort(li):
if len(li) < 2:
return li
pivot = li[0]
lo = [x for x in li if x < pivot]
hi = [x for x in li if x > pivot]
return quicksort(lo) + pivot + quicksort(hi)
Calculating runtime for Quicksort will be somewhat more difficult than for Merge Sort as the size of the lists that are returned recursively depend on the selected pivot. Selecting a good pivot is an art in itself. The naïve method of consistently selecting the first element, kan easily be exploited by an adversary, by giving a list that is a reversed sorted list. In this case the runtime will be
Bubblesort
Traverses the list, comparing two and two elements and swapping places if necessary. Note the algorithim has to run through the list several times, worst case n times.
Best Case  Average Case  Worst Case 
Insertion Sort
Most common way for humans to sort cards. Take the first element, and place in an empty "sorted" list. Select the next unsorted element and place it accordingly to the first element depending on value. Iteratively insert element i from unsorted list into the correct place in the already sorted list of i1 elements.
Best Case  Average Case  Worst Case 
Selection sort
A terrible sorting algoritmm which searches through the entire list and selects the smallest element each time.
Best Case  Average Case  Worst Case 
Other Sorting Algorithms
Sorting algorithms that are not comparison based are not limited to having
Heapsort
There are several methods of orgainzing a heap. A maxheap is a binary tree where each node value is never higher than its parents value. A minheap is hte opposite, where no node is allowed a lower value than its parent. A heap can be built in
Methods for heap include:
Method  Runtime 
Buildmaxheap  
Extractmax  
Maxheapify  
Maxheapinsert  
Heapincreasekey  
Heapmaximum 
Heapsort builds a heap og places the highest element at the end of the list and maintains the heap with maxheapify.
Best Case  Average Case  Worst Case 
Counting sort
This algorithm assumes that an input is a whole number from a defined interval k. Counting sort counts how many elements which are less than or equal to the element which is to be sorted, and puts it into the correct place in th elist. This is a stable search algorithm.
Best Case  Average Case  Worst Case 
If
Radix sort
Radix sort assumes that the input is n elements with d digits, where each digit can have up to k different values. The algorithm starts usually with the least significant digit and sorts the list according to this value before moving on to the second least significant digit. If the sorting is based on a stable algorithm that sorts in
Best Case  Average Case  Worst Case 
Bucket sort
Bucket sort assumes that the input is generated from an arbitrary process that distributes the elements unifromly and independently across an intervall. Bucket sort divides the interval into n equally large buckets and distributes the n input values into the buckets. Each bucket is then individually sorted by using a sorting algorithm such as another bucket sort, insertion sort etc.
Best Case  Average Case  Worst Case 
Topological Sort
Topological sort is a sorting algorithm that is used to organize the nodes into a Directed Acyclic Graph (DAG). If there exists an edge
Graphs and Graph Algorithms
A graph is a mathematical structure that is used to model pairwise relations between objects. In other words: a graph is an overview over several small relations. In this course graphs are some of the most important datastructures and has several accompanying algorithms.
Representation
A graph can look like this:
How can wi represent this on a computer? In larger systems it can be relevant to do this object oriented, where an object representing a graph containts node objects which have pointers to neighbouring node objects. A more common method is through neighborlists or matrices.
Neighbor Lists
Given the graf G with nodes
This implies that there is an edge from the node before the colon (":") to each of te nodes in the list after the colon. This method of representing graphs fits well when a graph is sparse, meaning has few edges.
Neighbor Matrices
When we have several edgesin a graph (dense graphs), it is preferrable to represent this via a neighbor matrix. For a graph with
0 1 2 3 4 5

0  0 1 0 0 0 1
1  0 0 1 1 0 1
2  1 1 0 1 0 0
3  0 0 1 0 1 0
4  0 0 0 0 0 1
5  1 0 1 0 1 0
This matrix represents a graph G with nodes
Traversal
With a representation of a graph on the computer, it is now possible to traverse the elements of the matrix from beginning to end much like we traverse a list. The two most common methods of traversal are Breadth First Search (BFS) and Depth First Search (DFS).
Breadth First Search (BFS)
Breadth first search is a graph treversal algorithm that as it examines a node, it adds all of that nodes children to the queue. More precisely:
 Given a graph, a start node and an order to insert nodes, we create a queue and place the start node into that queue. The queue has at the moment only one element.
 As long as there is one or more elements in the queue, remove the first element from the queue (dequeue), potentially do something with the node, and add its neighbors to the queue in the order specified.
If you are searching for an element, the search can be terminated when the node you are searching for is found and dequeued.
Runtime:
Note on Traversal
When traversing breadth first write out nodes for each level in the tree from left to right.
Depth First Search (DFS)
DFS uses a stack instead of a queue Since a stack is LIFO, you push the children to the topmost node onto the stack until reaching a leaf node (dead end). The topmost node is then popped, handled and discarded before moving to the underlying node. More precisely:
 Given a graf, a starting node and an order to stack nodes, we create a stack and push the start node onto it.
 As long as there is one or more elements on the stack, pop the top element, and push the children onto the stack, in oposite orider. If the order of the children is A, B, C, then they are pushed onto the stack, C, B, A.
It is worth noting that by recording start and end times, DFS can be used for topological sorting.
Runtime:
Traversering
Inorder, Preorder og Postorder traversal visits each node in a tree by recursively visiting each nodes children from left to right.
One good way of remembering this is to think about when we insert the nodes into the list of visited nodes. We always start with the toppnode and then go down the left side of the graph, visualized below.
In a preorder traversal, we place the nodes into the list as we psas them on the left hand side down.
In the inorder traversal, we place the nodes into the list as we go through the node.
In the postorder traversal, we place the nodes into the list as we pass them on the right hand side up.
Traversersalmethod  Visualization  Result 
Preorder  F, B, A, D, C, E, G, I, H  
Inorder  A, B, C, D, E, F, G, H, I  
Postorder  A, C, E, D, B, H, I, G, F 
Minimal Spanning Trees
A minimal spanning tree is a tree that is within all the nodes exactly once, and has the lowest possible cumulative edge weight.
Kruskal
Kruskal's algorithm creates a tree by finding the smallest edges in the graph one by one, and creating a forest of trees. These trees are gradually merged together into one tree which becomes the minimal spanning tree. First the edge with the smallest weight is found and this edge is made into a tree. Then the algorithm looks for the second smallest edge weight and connects these two nodes. If these were two free nodes they are connected as a new tree; if one of them are connected to an existing tree, the second node is attached to that tree; and if both are in separate trees these two trees are merged; if both are in the same tree then the edge is ignored. This method continues until we have one complete tree with all nodes.
Best Case  Average Case  Worst Case 
Prim
Prim's algorithm creates a tree by starting in an arbitrary node and then adding the edge (and connecting node) with the smallest weight to tree. With now two nodes connected, the edge with the lowest weight that connects to either of the two nodes is added. This continues until all of the nodes have become a part of the tree. Runtime depends on the underlying datastructure, however the curriculum uses a binary heap.
Best Case  Average Case  Worst Case 
Shortest Path
Finding the shortest path is a common problem. For example if one is to drive the shortest (in meters) from one place to another, or to find the path through an electrical circuit with the smallest cumulative resistance.
In general, shortest path problems are divided into subproblems where we look at the shortest stretches between nodes.
Typical issues of concern when selecting an algorithm is:

Is the graph directed or undirected (ordinary)?

Do cycles exist in the directed graph? If so, there will always be a shorter path that does not include the cycle.

Are there negative edges?

Are negative cycles created? In this case, it becomes impossible to reach certain nodes.
OnetoAll
It is often important to know how a graph can be traversed, and find the distance between one and several nodes.
Relax
Assumes a list of distances to for now best routes to each node (v.d) and which node one would be coming from (v.π). Relax checks if the edge from u to v gives an improvement, and in that case updates the estimates v.d = u.d+w(u,v) and v.π = u.
Dijkstra's algorithm
Dijkstra's algorithm only works if all edges are nonnegative.
Best Case  Average Case  Worst Case 
If there exist negative cycles, this algorithm will not termniate as normal. It is possible to add an alternative stopping method, however the result may be wrong.
Dijkstra is most effective when used in a heap. Implementation in other structures can cost higher runtimes and are not curriculum.
How it works:
 Initialize distances. Set the startnode to 0 and all others to +inf
 Initialize visited. Set the startnode to visited, and all other to not visited.
 Look at all neighbors, calculate distances and update distances.
 Update distances.
 Go to the node with the lowest distance value from start, and mark it as read.
 Repeat steps 35 until all nodes are visited or an specific end node is visited.
In python:
def dijkstra(G,start): #G er grafen, start er startnoden
pq = PriorityQueue() # initialiserer en heap
start.setDistance(0) # Initialiserer startnodens avstand
pq.buildHeap([(node.getDistance(),node) for node in G]) # Lager en heap med alle nodene
while not pq.isEmpty():
currentVert = pq.delMin() # velger greedy den med kortest avstand
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() + currentVert.getWeight(nextVert) #kalkulerer nye avstander
if newDist < nextVert.getDistance():
nextVert.setDistance( newDist ) # oppdaterer avstandene
nextVert.setPred(currentVert) # Oppdaterer foreldrene til den med kortest avstand
pq.decreaseKey(nextVert,newDist) # lager heapen på nytt så de laveste kommer først.
BellmanFord
Unlike Dijkstra, BellmanFord works also with negative edges.
Best Case  Average Case  Worst Case 
BellmanFord is defined recursively. In contrast to Dijkstra, BellmanFord relaxes all edges, meaning it updates all edges for each iteration. This helps discover any potential negative cycles. All edges are relaxed
How it works:
 Initialize the algorithm by setting the distance from the startnode to 0, and all others to +inf.
 Compare all distances, and update each node with the new distance.
 Check for negative cycles.
In python:
def bellman_ford(G, s) # G er grafen, med noder og kantvekter. s er startnoden.
distance = {}
parent = {}
for node in G: # Initialiserer startverdier
distance[node] = float('Inf')
parent[node] = None
distance[s]=0 # initialiserer startnoden
# relax
for (len(G)1):
for u in G: # fra node u
for v in G[u]: # til naboene
if distance[v] > distance[u] + G[u][v]: # Sjekker om avstanden er mindre
distance[v] = distance[u] + G[u][v] # hvis ja, oppdaterer avstanden
parent[v]=u # og oppdaterer parent
# sjekk negative sykler
for u in G:
for v in G[u]:
if distance[v] > distance[u] + G[u][v]:
return False
DAG shortest path
The shortest path from one to all. With a given DAG(Directive Acylic Graph) it is possible to do a topological Sort before traversing the sorted graph and relaxing all edges that are traversed.
Psuedocode from Cormen:
1 DAGSHORTESTPATHS(G, w, s)
2 for each vertex v in G.V
3 v.d = inf # Distance
4 v.p = null # Parent
5 s.d = 0
6 for each vertex u in G.v, where G.v is topologically sorted
7 for each adjacent vertex v to u
8 if v.d > u.d + w(u, v) # Relax
9 v.d = u.d + w(u, v)
10 v.p = u
Best Case  Average Case  Worst Case 
All to All
FloydWarshall
FW works even if there are negative edges, but no negative cycles. The nodes must be stored as a neigbor matrix not a list.
Psuedocode from wikipedia:
1 let dist be a V × V array of minimum distances initialized to ∞ (infinity)
2 for each vertex v
3 dist[v][v] ← 0
4 for each edge (u,v)
5 dist[u][v] ← w(u,v) // the weight of the edge (u,v)
6 for k from 1 to V
7 for i from 1 to V
8 for j from 1 to V
9 if dist[i][j] > dist[i][k] + dist[k][j]
10 dist[i][j] ← dist[i][k] + dist[k][j]
11 end if
In Python:
def FloydWarshall(W):
n = len(W)
D = W
PI = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
if(i==j or W[i][j] == float('inf')):
PI[i][j] = None
else:
PI[i][j] = i
for k in range(n):
for i in range(n):
for j in range(n):
if D[i][j] > D[i][k] + D[k][j]:
D[i][j] = D[i][k] + D[k][j]
PI[i][j] = PI[k][j]
return (D,PI)
Best Case  Average Case  Worst Case  
linear arr  
binary he  
binary he 
The Algorithm creates matrix
Max Flow
Flow can be visualized by forexample a pipe system to deliver water to a city, or as a network with differing capacity on the various cables. Max fow is the maxium net capacity that actually flows through the network. There may exist some critical pipes (edges) with very low capacity, bottlenecking the entire network no matter the size of the other pipes. Max flow is achieved when there exists no more augumenting paths.
Flow Network
A flow network is a directed graf where all the edges have a nonnegative capacity. Additionally, it is required that if there exists an edge between u and v, there exists no edge in the opposite direction from v to u. A flow network has a source, s, and a sink, t. The source can be seen as the starting node and the sink as the end node. The graph is not divided so for all v there exists a route s ~v~t. All nodes except from s have atleast one inbound edge. All nodes except the source and the sink have a net flow of 0 (all inbound flow = all outbound flow).
A flow network can have several sources and sinks. To eliminate this problem, a super source and super sink are created and linked up to all respective sources and sinks with edges that have infinite capactiy. This new network with only one source and sink is much easier to solve.
Residual Network
The residual network is the capacity left over:
To keep an eye on the residual network is useful. If we send 1000 liters of water from u to v, and 300 liters from v to u, it is enough as sending 700 from u to v to achieve the same result.
Augumenting Path
An augumenting path is a path from the source to the sink that increases the total flow in the network. It can be found by looking at the residual netowrk.
Minimal cut
A cut in a flow network divides the graph in two, S and T. It is useful to look at the flow through this cut:
Of all possible cuts, we want to see the cut with the smallest flow, as this is the bottleneck of the network. Proof exists that show that finding the minimal cut simultaneously gives us the maximum flow through the network.
FordFulkersons method
Given flow f, in each iteration of FordFulkerson we find an augumenting path p, and use p to modify f.
Best Case  Average Case  Worst Case 
EdmondsKarp
EdmondsKarp is FordFulkerson's method where BFS is the traversal method. This ensures a runtime of
Whole Number Theorem
If all capacities in the flow network are whole numbers, then FordFulkerson's method will find a max flow with a whole number value, and the flow between all neighbor nodes will have whole number values.
Dynamic Programming
Dynamic programming divides up problems into smaller subproblems, just like divide and conquer. DP is used when:  optimal substructure:  these subproblems overlap
It is often possible to use divide and conquer on these types of problems, but must often a lot of redundant work is done as the same subproblem has to be solved several times. DP solves the subproblem once, and then uses the result each time it is needed.
DP is usually used for Optimization problems, but as there are several optimal solutions its an optimal solution.
4 Steps:
 Characterize the strucutre of the optimal solution.
 Recursively define the value of an optimal solution.
 Compute the value of an optimal solution, typically in a bottom up fashion.
 Construct an optimal solution from computed information.
Longest common substring
Is solved by DP from the bottom up, by looking at the last element i each list.
Rodcutting
Given a rod with length n, and a list of prices for all lengtsh shorter than n. Decide the max profit you can achieve by cutting the rod up and selling it.
We can cut up a rod on length n in
Greedy Algorithms
Some times a DP is a bit overkill. Greedy algorithms choose the solution that seems the best righ tthen and there, and moves on. This does not always leed to the best solution, but for many problems this works fine. Minimal spanning trees is an example of a greedy method. Greedy algorithms solve the problem if it has the following attributes:

$Greedychoice\ property$ We can make a choice that seems optimal at the time and solve the subproblems that occur later. The greedy choices can not be dependent on future choices nor all existing solutions. It simply iteratively takes greedy choices and reduces the given problem to a smaller one. 
$Optimal\ substructure$ Optimal solitions to a problem incorporate optimal solutions to related subproblems, which we may solve independently.
Planning activities
Choose as many nonoverlapping activities as possible. Assume that they are sorted by ending time and use a greedy algorithm to select them.
Huffman's algorithm
Huffman's algorithm is a greedy algorithm with the intent to minimize saving space to a known sequence of symbols. Each symbol can be represented by a binary code. The given code is dependent on the frequency the symbol, where the more frequent terms get the shorter bits. Depending on term distribution, this reduces the space required by 2090%.
Huffman is performed by always summing the two nodes with the smallest frequency values, and then using the num of these as the value of a new node. By branching left with
Runtime:
Best case  Average case  Worst case 
One version of Huffmann coding can look like this:
Multithreading
The basics of Multithreading
Concurrency keywords
 Spawn  used to start a parallel thread, allowing tha parent thread to continue with the next line while the child thread runs its subproblem
 Sync  A procedure cannot safely use the values returned by its spawned children until after it executes a sync statement. This keyword indicates that the program must wait until both threads are finished allowing for the correct variables to syncronize
 Serializaion  the serial algorithm that results from deleting the multithreaded keywords: spawn, sync, and parallel.
 Nested parallelism  occurs when the keyword spawn precedes a procedure call. A child thread is spawned to solve the subproblem which in turn runs their own spawn subproblems, potentially creating a vast tree of subcomputations, all excecuting in parallel.
 Logical parallelism  concurrency keywords express logical parallelsism, indicating which parts of the computation may procedd in parallel. At runtime it is upt o a scheduler to determine which subcomputations actually run concurrently.
Performance Measures
Two metrics, work and span.
Work  The work of a multithreaded computation is the total time to execute the entire computatin on one processor. It is the sum of the times taken by each strand.
Span  The span is the longest time to execute the strands along any path of the DAG. Again for a DAG in which each strand takes unit time, the span equals the number of vertices on a longest or critical path in the DAG. Given that time to calculate is denoted as
 Rewriting the work law we get
$T_1/T_P \leq P$ , stating that the speedup on P processors can at most be P.  If
$T_1/T_P = \theta(P)$ implies linear speed up 
If
$T_1/T_P = P$ implies perfect linear speed up 
The ratio
$T_1/T_\infty$ of the work to the span gives the parallelism of the multithreaded computation.
Problem Complexity
P, NP, NPC
The question connected to whether
We know that
P  Polynomial time  
NP  Nondeterministic polynomial time  
NPC  Nondeterministic polynomial time complete  
NPH  Nondeterministic polynomial time hard 
That a problem is P, implies it is solvable in polynomial time. An NPproblem is a problem that we can prove is true (verifiable), at polynomial time. If it is possible to falsify the solution in polynomial time, the problem is a part of the coNPclass. NPHard (NPH) problems cannot be solved in polynomial time. It is said that this class of problems are atleast as difficult as the most difficult problem in the NPclass. In other terms, they are problems which can be reduced from NPproblems in polynomial time, but not necessarily allows themselves to be verified in polynomial time with a given solution. NPhard problems that allow themselves to be verified in polynomial time are called NPcomplete.
Reducibilityrelation
To understand the proof technique used to prove a problem is NPC, a few definitions need to be in place. One of these is the reducibilityrelation
Cormen et al., exemplifies that the linear equation
Some known NPC problems
Some common examples of NPC problems include:
 CircuitSAT
 SAT
 3CNFSAT
 Cliqueproblemet
 VertexCover
 HamiltonCycle
 Travelling Salesman (TSP)
 SubsetSum
But how can we prove a poblem is NPC?
Cormen et al. divides this into two parts:
 Prove that the problem belongs to the NPclass. Use a certification to prove that the solution is verified in polynomial time.
 Prove the problem is NPhard. This is done through polynimial time reduction.
Given
This connection is illustrated in the figure below:
Given that you are trying to prove that TSP is an NPCproblem:
 Prove that TSP
$\in$ NP. The certification you use can be a sequence of n nodes that you shall visit on your trip. If the sequence just consists of unique nodes (we do not visit the same city more than oce) then we can sum up the costs and verify the total cost is less than a given number k.  Prove that TSP is NPhard. If you have understood what the different problems described above, then you will recognize that TSP is a Hamilton Cycleproblem (given an undireted graph G, there exists a cucle that contains all the nodes only once, and where the starting node = the end node). We know that TSP is atleast as difficult to solve as a the Hamcycle problem (as Hamcycle is a subproblem of TSP). Given that we already have proved that the Hamcycle problem is NPhard, we can show with polynomial time reduction that TSP is also NPhard (since we reduce Hamcycle to TSP in polynimial time, then TSP is NPH)
As most people now believe that
Runtimes for curriculum algorithms
Sorting and selection
$n$ is the number of elements that are being handled.$k$ is the highest value possible.$d$ is the max munber of digits an element can have.
Algorithm  Best case  Average case  Worst case  Space Complexity Worst Case  Stable 
Merge sort  Yes  
Quick sort  No  
Heap sort  No  
Bubble sort  Yes  
Insertion sort  Yes  
Selection sort  No  
Bucket sort  Yes  
Counting sort  Yes  
Radix sort  Yes*  
Select  NA  NA  
Randomized select  NA  NA 
 Radix sort need require a stable subsort for itself be stable
Heapoperations
Operations  Runtime 
Insert  
Delete  
Build  
Maxheaplify  
Increasekey  
Maximum 
Graphoperations
Algorithm  Best case  Average case  Worst case 
Topological sort  
Depthfirstsearch  
Breadthfirstsearch  
Prim's  
Kruskal's  
BellmannFord's  
Dijkstra's  
FloydWarshall's  
DAGshortestpath 