Design and Analysis of Algorithm
Design and Analysis of Algorithm
Algorithm
Analysis
In this algorithm, we are using two loops, one is within another. Hence, the
complexity of this algorithm is O(n2).
Example
We have to find a sequence of jobs, which will be completed within their deadlines
and will give maximum profit. Each job is associated with a deadline and profit.
To solve this problem, the given jobs are sorted according to their profit in a
descending order. Hence, after sorting, the jobs are ordered as shown in the following
table.
From this set of jobs, first we select J2, as it can be completed within its deadline and
contributes maximum profit.
In the next clock, J4 cannot be selected as its deadline is over, hence J3 is selected as
it executes within its deadline.
Thus, the solution is the sequence of jobs (J2, J1, J3), which are being executed
within their deadline and gives maximum profit.
Dijkstra's Algorithm
It is a greedy algorithm that solves the single-source shortest path problem for a
directed graph G = (V, E) with nonnegative edge weights, i.e., w (u, v) ≥ 0 for each
edge (u, v) ∈ E.
Algorithm
AlgorithmDijkstra (v0, W, dist, n)
// v0 is the source vertex, W is the adjacency matrix to store the weights of the links,
dist[k] is the array
to store the shortest path to vertex k, n is the number of vertices//
{
for (i = 1 ; i < = n ; i ++){
S[i] = 0; // Initialize the set S to empty i.e. i is not inserted into the set//
dist[i] = w(v0,i) ; //Initialize the distance to each node
}
S[vo] = 1; dist[v0] = 0;
for (j = 2; j<= n; j++) {
choose a vertex u from those vertices not in S such that dist [u] is minimum.
S[u] = 1;
for (each z adjacent to u with S[z] = 0) {
if(dist[z] >dist [u] + w[u, z])
dist[z] = dist [u] + w[u, z];
}
}
}
Analysis: The running time of Dijkstra's algorithm on a graph with edges E and
vertices V can be expressed as a function of |E| and |V| using the Big - O notation.
The simplest implementation of the Dijkstra's algorithm stores vertices of set Q in an
ordinary linked list or array, and operation Extract - Min (Q) is simply a linear search
through all vertices in Q. In this case, the running time is O (|V2 |+|E|=O(V2 ).
Example
Use Dijkstras algorithm to find the shortest path from A to each of the other six
vertices in the graph: