Greedy Algorithms

Pseudocode for Unweighted Interval Scheduling

UIS(s, f){ // s and f hold the start and finish times
    n = number of jobs
    Sort all jobs by finish time

    C = {1} // C is the set of compatible tasks
    lastChosen = 1 // index of last job chosen

    for(i = 2...n)
        if( s(i) >= f(lastChosen) ){
             C.add(i)
             lastChosen = i
        }
    }
    return C
}


Pseudocode for Huffman Coding

HUFFMAN(C){//C contains the characters and their frequencies
    n = number of characters
    Q // a minimum priority queue
    T // an empty binary tree

    for(i=1...n)
        Q.push(c_i, freq(c_i))
    }

    for(i=1...n-1)
        x = Q.pop()
        y = Q.pop()
        Create a new node z in T
        z.left = x
        z.right = y
        Q.push(z, freq(x) + freq(y))
    }
    return T
}


DIJKSTRAS(G, s){ //G is the graph, s is the source node
    Q // a minimum priority queue
    dist // distance from s, initialize to infinity
    prev // previous node on shortest path, initialize to null

    dist[s] = 0
    for(v in V)
        Q.push(v, dist[v])
    }

    while(Q not empty)
        u = Q.pop()// Found shortest path to u
        for v in AdjacencyList(u){
            alt = dist[u] + w(u,v) // Is this better than what we've found so far?
            if(alt < dist[v]){
                dist[v] = alt
                prev[v] = u
                Q.changePriority(v, alt)
            }
        }
    }
    return dist, prev
}


PRIMS_MST(G){ //G is the graph
    Q // a minimum priority queue
    dist // distance from s, initialize to infinity
    prev // previous node in the MST, initialize to null

    dist[r] = 0 //some randomly chosen node in the graph
    for(v in V)
        Q.push(v, dist[v])
    }

    while(Q not empty)
        u = Q.pop()// Node with the lowest edge cost
        for v in AdjacencyList(u){
            alt = w(u,v) // Is this better than what we've found so far?
            if(v is in Q and alt < dist[v]){
                dist[v] = alt
                prev[v] = u
                Q.changePriority(v, alt)
            }
        }
    }
    return dist, prev
}