ada lab file

Upload: newjobs

Post on 02-Jun-2018

237 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 Ada Lab File

    1/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 1

    OBJECTIVE: PROGRAM TO IMPLEMENT SELECTION SORT.

    ALGORITHM USED:

    Selection-Sort (A)

    1 fori 1 tolength[A]1

    2 domin i

    3 forj i + 1 tolength[A]

    4 doifA[j] < A[min]

    5 thenmin = j

    6 swap A[i] with A[min]

    FUNCTIONALITY: It works as follows: first find the smallest in the array andexchange it with the element in the first position, then find the second smallest

    element and exchange it with the element in the second position, and continue in this

    way until the entire array is sorted.

    C++ CODE IMPLEMENTATION:

    //PROGRAM TO IMPLEMENT SELECTION SORT

    #include

    using namespace std;

    int main()

    {

    int num;

    double a[25],temp;

    int i, j;

    coutnum;

    cout

  • 8/10/2019 Ada Lab File

    2/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    min=j;

    }

    temp=a[i];

    a[i]=a[min];

    a[min]=temp;

    }

    for(i=0;i

  • 8/10/2019 Ada Lab File

    3/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 2

    OBJECTIVE: PROGRAM TO IMPLEMENT BUBBLE SORT.

    ALGORITHM USED:

    Bubble-Sort (A)

    1 fori 1 tolength[A]

    2 doforj length[A] down toi + 1

    3 doifA[j] < A[j - 1]

    4 thenswap A[j] A[j - 1]

    FUNCTIONALITY: It works by repeatedly stepping through the list to be sorted,

    comparing each pair of adjacent items and swapping them if they are in the wrong

    order. The pass through the list is repeated until no swaps are needed, which indicates

    that the list is sorted.

    C++ CODE IMPLEMENTATION:

    //PROGRAM TO IMPLEMENT BUBBLE SORT

    #include

    using namespace std;

    int main()

    {

    int num;

    double arr[25],temp;

    int i, j;

    coutnum;

    cout

  • 8/10/2019 Ada Lab File

    4/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    cout

  • 8/10/2019 Ada Lab File

    5/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 3

    OBJECTIVE: PROGRAM TO IMPLEMENT BREADTH FIRST SEARCH (BFS).

    ALGORITHM USED:

    BFS (V, E, s)

    for each uin V {s}

    do color[u] WHITE

    color[s] GRAY

    Q {}

    ENQUEUE(Q,s)

    while Q is non-empty

    do u DEQUEUE(Q)

    for each vadjacent to u

    do if color[v] WHITE

    then color[v] GRAY

    ENQUEUE(Q, v)

    DEQUEUE(Q)

    color[u] BLACK

    where

    V = Set of Vertices

    E =Set of Edges

    s = Source vertex

    color[] = Colour array to keep track of the visiting, unvisited and visited node

    FUNCTIONALITY:

    In graph theory, breadth-first search (BFS) is a graph search algorithm that begins at

    the root node and explores all the neighbouring nodes. Then for each of those nearest

    nodes, it explores their unexplored neighbour nodes, and so on, until it finds the goal.

    From the standpoint of the algorithm, all child nodes obtained by expanding a node

    are added to a FIFO (i.e., First In, First Out) queue. In typical implementations, nodes

    that have not yet been examined for their neighbours are placed in some container

    (such as a queue or linked list) called "open" and then once examined are placed in

    the container "closed".

  • 8/10/2019 Ada Lab File

    6/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    C++ CODE IMPLEMENTATION:

    //PROGRAM TO IMPLEMENT BFS

    #include "iostream"

    using namespace std;

    int a[20];

    int c=0;

    int co=0;

    void enque(int item)

    {

    a[c++]=item;

    }

    int deque()

    {

    return a[co++];

    }

    int qIsNotEmpty()

    {

    if(c==co)

    return 0;

    else

    return 1;

    }

    int main()

    {

    int num;

    int d;

    int ed;

    int s;

    int m;

    int **matrix;

    char *arr;

    cout

  • 8/10/2019 Ada Lab File

    7/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    arr[i]='w';

    for(int j=0;j

  • 8/10/2019 Ada Lab File

    8/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    OUTPUT:

  • 8/10/2019 Ada Lab File

    9/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 4

    OBJECTIVE: PROGRAM TO IMPLEMENT DEPTH FIRST SEARCH (DFS).

    ALGORITHM USED:

    DFS (V, E)

    for each vertex uin V[G]

    do color[u] WHITE

    time 0

    for each vertex uin V[G]

    do if color[u] WHITE

    then DFS-Visit(u)

    DFS-Visit(u)

    color[u] GRAY

    time time + 1

    d[u] time

    for each vertex vadjacent to u

    do if color[v] WHITE

    then DFS-Visit(v)

    color[u] BLACK

    V = Set of Vertices

    E = Set of edges

    color[] = colour array to keep track of the visiting, unvisited and visited node

    FUNCTIONALITY:

    Depth-first search selects a source vertex sin the graph and paint it as "visited." Now

    the vertex sbecomes our current vertex. Then, we traverse the graph by considering

    an arbitrary edge (u, v) from the current vertex u. If the edge (u, v) takes us to a

    painted vertex v, then we back down to the vertex u. On the other hand, if edge (u, v)

    takes us to an unpainted vertex, then we paint the vertex vand make it our current

    vertex, and repeat the above computation. Sooner or later, we will get to a dead end,

    meaning all the edges from our current vertex utakes us to painted vertices. This is a

    deadlock. To get out of this, we back down along the edge that brought us here to

    vertex uand go back to a previously painted vertex v. We again make the vertex vour

    current vertex and start repeating the above computation for any edge that we missed

    earlier.

    If all of v's edges take us to painted vertices, then we again back down to the vertex

    we came from to get to vertex v, and repeat the computation at that vertex. Thus, we

    continue to back down the path that we have traced so far until we find a vertex that

    has yet unexplored edges, at which point we take one such edge and continue the

  • 8/10/2019 Ada Lab File

    10/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    traversal. When the depth-first search has backtracked all the way back to the original

    source vertex, s, it has built a DFS tree of all vertices reachable from that source. If

    there still undiscovered vertices in the graph then it selects one of them as the source

    for another DFS tree. The result is a forest of DFS-trees.

    C++ CODE IMPLEMENTATION:

    // PROGRAM TO IMPLEMENT DFS

    #include "iostream"

    using namespace std;

    void dfs_visit(int **matrix, char *arr,int num, int d)

    {

    arr[d]='g';

    cout

  • 8/10/2019 Ada Lab File

    11/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    for(int j=0;j

  • 8/10/2019 Ada Lab File

    12/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 5

    OBJECTIVE: PROGRAM TO IMPLEMENT KRUSKAL ALGORITHM.

    ALGORITHM USED:

    KRUSKAL (G)

    1. A = Empty

    2. for each v G.V

    3. MAKE-SET(v)

    4. for each (u, v) ordered by weight(u, v), increasing:

    5.

    if FIND-SET(u) FIND-SET(v):

    6. A = A {(u, v)}

    7.

    UNION(u, v)

    8.

    return A

    FUNCTIONALITY:

    Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree

    for a connected weighted graph. This means it finds a subset of the edges that forms a tree

    that includes every vertex, where the total weight of all the edges in the tree is minimized.

    Steps:

    1) Create a forest F (a set of trees), where each vertex in the graph is a separate tree

    2) Create a set S containing all the edges in the graph

    3) while S is nonempty and F is not yet spanning

    - remove an edge with minimum weight from S

    - if that edge connects two different trees, then add it to the forest, combining two trees

    into a single tree

    - otherwise discard that edge.

    At the termination of the algorithm, the forest forms a minimum spanning forest of the graph.

    If the graph is connected, the forest has a single component and forms a minimum spanning

    tree.

  • 8/10/2019 Ada Lab File

    13/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    C++ CODE IMPLEMENTATION:

    //PROGRAM TO IMPLEMENT KRUSKAL ALGORITHM

    using namespace std;

    #include

    #include

    class kruskal

    {

    private:

    int n; //no of nodes

    int noe; //no edges in the graph

    int graph_edge[100][4];

    int tree[10][10];

    int sets[100][10];

    int top[100];

    public:

    void read_graph();

    void initialize_span_t();

    void sort_edges();

    void algorithm();

    int find_node(int );

    void print_min_span_t();

    };

    void kruskal::read_graph()

    {

    cout

  • 8/10/2019 Ada Lab File

    14/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    cin>>w;

    if(w!=0)

    {

    noe++;

    graph_edge[noe][1]=i;

    graph_edge[noe][2]=j;

    graph_edge[noe][3]=w;

    }

    }

    }

    // print the graph edges

    cout

  • 8/10/2019 Ada Lab File

    15/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    // print the graph edges

    cout

  • 8/10/2019 Ada Lab File

    16/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    {

    cout

  • 8/10/2019 Ada Lab File

    17/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    OUTPUT:

  • 8/10/2019 Ada Lab File

    18/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 6

    OBJECTIVE: PROGRAM TO IMPLEMENT PRIM ALGORITHM.

    ALGORITHM USED:

    PRIM(V,E,w,r)

    1. Q= Empty

    2. For each u belongs to V

    3. do key[u]= Infinite

    4.

    parent[u]=NIL

    5. INSERT (Q,u)

    6. DECREASE-KEY(Q,r,0)

    7.

    While Q !=Empty

    8. Do u=EXTRACT-MIN(Q)

    9. For each v belongs to Adj[u]

    10.Do if v belongs to Q and w(u,v) < key[v]

    11.

    then parent[v]=u

    12.DECREASE-KEY(Q,v,w(u,v))

    where,

    V= Subset of Vertices

    E= Subset of Edges

    w(u,v)= Weight of Edge (u,v).

    key[u]= Key Value of u Vertex

    FUNCTIONALITY:

    Prim's algorithm is agreedy algorithm that finds aminimum spanning tree for aconnected

    weightedundirected graph.This means it finds a subset of theedges that forms atree that

    includes everyvertex,where the total weight of all theedges in the tree is minimized.

    1. Initialize a tree with a single vertex, chosen arbitrarily from the graph.

    2. Grow the tree by one edge: Of the edges that connect the tree to vertices not yet in the

    tree, find the minimum-weight edge, and transfer it to the tree.

    3. Repeat step 2 (until all vertices are in the tree).

    http://en.wikipedia.org/wiki/Greedy_algorithmhttp://en.wikipedia.org/wiki/Minimum_spanning_treehttp://en.wikipedia.org/wiki/Connected_graphhttp://en.wikipedia.org/wiki/Weighted_graphhttp://en.wikipedia.org/wiki/Undirected_graphhttp://en.wikipedia.org/wiki/Edge_%28graph_theory%29http://en.wikipedia.org/wiki/Tree_%28graph_theory%29http://en.wikipedia.org/wiki/Vertex_%28graph_theory%29http://en.wikipedia.org/wiki/Graph_theoryhttp://en.wikipedia.org/wiki/Graph_theoryhttp://en.wikipedia.org/wiki/Vertex_%28graph_theory%29http://en.wikipedia.org/wiki/Tree_%28graph_theory%29http://en.wikipedia.org/wiki/Edge_%28graph_theory%29http://en.wikipedia.org/wiki/Undirected_graphhttp://en.wikipedia.org/wiki/Weighted_graphhttp://en.wikipedia.org/wiki/Connected_graphhttp://en.wikipedia.org/wiki/Minimum_spanning_treehttp://en.wikipedia.org/wiki/Greedy_algorithm
  • 8/10/2019 Ada Lab File

    19/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    C++ CODE IMPLEMENTATION:

    //PROGRAM TO IMPLEMENT PRIM ALGORITHM

    #include

    using namespace std;

    class prims

    {

    private:

    int n; //no of nodes

    int graph_edge[250][4]; //edges in the graph

    int g; //no of edges in the graph

    int tree_edge[250][4]; //edges in the tree

    int t; //no of edges in the tree

    int s; //source node

    //Partition the graph in to two sets

    int T1[50],t1; // Set 1

    int T2[50],t2; // Set 2

    public:

    void input();

    int findset(int);

    void algorithm();

    void output();

    };

    void prims::input()

    {

    cout

  • 8/10/2019 Ada Lab File

    20/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    g++;

    graph_edge[g][1]=i;

    graph_edge[g][2]=j;

    graph_edge[g][3]=w;

    }

    }

    }

    // print the graph edges

    cout

  • 8/10/2019 Ada Lab File

    21/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    // Find the least cost edge

    int min=9999;

    int p;

    int u,v,w;

    for(i=1;igraph_edge[i][3])

    {

    min=graph_edge[i][3];

    u=graph_edge[i][1];

    v=graph_edge[i][2];

    w=graph_edge[i][3];

    p=i;

    }

    }

    }

    //break if there is no such edge

    cout

  • 8/10/2019 Ada Lab File

    22/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    t1++;

    int m;

    if(findset(v)==2)

    {

    T1[t1]=v;

    m=v;

    }

    else if(findset(u)==2)

    {

    T1[t1]=u;

    m=u;

    }

    int x;

    for(x=1;T2[x]!=m;x++);

    for(;x

  • 8/10/2019 Ada Lab File

    23/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    {

    cout

  • 8/10/2019 Ada Lab File

    24/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    OUTPUT:

  • 8/10/2019 Ada Lab File

    25/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

  • 8/10/2019 Ada Lab File

    26/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 7

    OBJECTIVE: PROGRAM TO PERFORM OPERATIONS ON RED-BLACK TREE.

    ALGORITHM USED:

    RED-BLACK TREE INSERTION

    RB-INSERT(T, z)

    y nil[T ]x root[T ]while x _= nil[T ]do y xif key[z] < key[x]then x left[x]else x right[x]

    p[z] yif y = nil[T ]then root[T ] zelse if key[z] < key[y]then left[y] zelse right[y] zleft[z] nil[T ]

    right[z] nil[T ]color[z] RED

    RB-INSERT-FIXUP(T, z)

    RB-INSERT-FIXUP(T, z)while color[p[z]] = RED

    do if p[z] = left[p[p[z]]]then y right[p[p[z]]]if color[y] = RED

    then color[p[z]] BLACK_ Case 1color[y] BLACK_ Case 1

    color[p[p[z]]] RED_ Case 1z p[p[z]] _ Case 1else if z = right[p[z]]then z p[z] _ Case 2LEFT-ROTATE(T, z) _ Case 2

    color[p[z]] BLACK_ Case 3color[p[p[z]]] RED_ Case 3RIGHT-ROTATE(T, p[p[z]]) _ Case 3else (same as then clausewith .right. and .left. exchanged)

    color[root[T ]] BLACK

  • 8/10/2019 Ada Lab File

    27/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    RED-BLACK TREE DELETION

    RB-DELETE(T, z)

    if left[z] = nil[T] or right[z] = nil[T ]then y z

    else y TREE

    -SUCCESSOR

    (z)if left[y] _= nil[T ]then x left[y]else x right[y]p[x] p[y]

    if p[y] = nil[T ]then root[T ] xelse if y = left[p[y]]then left[p[y]] xelse right[p[y]] x

    if y _= zthen key[z] key[y]

    copy y.s satellite data into zif color[y] = BLACKthen RB-DELETE-FIXUP(T, x)

    return y

    RB-DELETE-FIXUP(T, x)

    while x _= root[T ] and color[x] = BLACKdo if x = left[p[x]]then w right[p[x]]if color[w] = RED

    then color[w] BLACK_ Case 1color[p[x]] RED_ Case 1LEFT-ROTATE(T, p[x]) _ Case 1

    w right[p[x]] _ Case 1if color[left[w]] = BLACK and color[right[w]] = BLACKthen color[w] RED_ Case 2x p[x] _ Case 2else if color[right[w]] = BLACK

    then color[left[w]] BLACK_ Case 3color[w] RED_ Case 3RIGHT-ROTATE(T,w) _ Case 3w right[p[x]] _ Case 3color[w] color[p[x]] _ Case 4

    color[p[x]] BLACK_ Case 4color[right[w]] BLACK_ Case 4

    LEFT-ROTATE(T, p[x]) _ Case 4x root[T ] _ Case 4else (same as then clause with .right. and .left. exchanged)

    color[x] BLACK

  • 8/10/2019 Ada Lab File

    28/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    FUNCTIONALITY:

    A red-black tree is a binary search tree + 1 bit per node: an attribute color, which

    is either red or black.

    All leaves are empty (nil) and colored black.

    We use a single sentinel, nil[T ], for all the leaves of red-black tree T .

    color[nil[T ]] is black.

    The root.sparent is also nil[T ].

    Red Black tree Properties:

    1. Every Node is either Red or black.

    2. The root is Black.

    3. Every leaf is Black.

    4.

    If a node is red, then both its children are black.

    5.

    For each node, all paths from the node to descendent leaves contain the same number

    of black nodes.

    C++ CODE IMPLEMENTATION:

    //PROGRAM TO PERFORM OPERATIONS ON RED-BLACK TREE.

    using namespace std;

    #include

    #include

    class node

    {

    public:

    node *l , *r, *p;

    int v,c;

    node()

    { c=0; }

    };

    class rbtree

    {

    public:

    node *root, *nilt;

    rbtree()

    {

    nilt=new node();

    nilt->c=1;

    root=nilt;

  • 8/10/2019 Ada Lab File

    29/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    }

    void lrotate(node *x)

    {

    node *y=x->r;

    x->r=y->l;

    y->l->p=x;

    y->p=x->p;

    if(x->p==nilt)

    root=y;

    else

    {

    if(x==x->p->l)

    x->p->l=y;

    else x->p->r=y;

    }

    y->l=x;

    x->p=y;

    }

    void rrotate(node *x)

    {

    node *y=x->l;

    x->l=y->r;

    y->r->p=x;

    y->p=x->p;

    if(x->p==nilt)

    root=y;

    else

    {

    if(x==x->p->r)

    x->p->r=y;

    else x->p->l=y;

    }

    y->r=x;

    x->p=y;

    }

    void insertfixup(node *z)

  • 8/10/2019 Ada Lab File

    30/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    {

    node *y=NULL;

    coutp==z->p->p->l)

    {

    coutp->r;

    if(y->c==0)

    {

    z->p->c=1;

    y->c=1;

    z->p->p->c=0;

    }

    else

    {

    if(z==z->p->r)

    {

    z=z->p;

    lrotate(z);

    }

    z->p->c=1;

    z->p->p->c=0;

    rrotate(z->p->p);

    }

    }

    else

    {

    coutp->l;

    if(y->c==0)

    {

    coutc=1;

    y->c=1;

    z->p->p->c=0;

    }

  • 8/10/2019 Ada Lab File

    31/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    else

    {

    if(z==z->p->l)

    {

    coutp->c=1;

    z->p->p->c=0;

    coutv=x;

    while(t!=nilt)

    {

    if(x>t->v)

    {

    y=t;

    t=t->r;

    }

    else if(xv)

  • 8/10/2019 Ada Lab File

    32/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    {

    y=t;

    t=t->l;

    }

    else

    {

    coutp=y;

    }

    insertfixup(n);

    }

    void delfixup(node *x)

    {

    node *w=NULL;

    while(x!=root && x->c==1)

    {

    if(x==x->p->l)

  • 8/10/2019 Ada Lab File

    33/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    {

    w=x->p->r;

    if(w->c==0)

    {

    w->c=1;

    x->p->c=0;

    lrotate(x->p);

    w=x->p->r;

    }

    if(w->l->c==1 && w->r->c==1)

    {

    w->c=0;

    x=x->p;

    }

    else

    {

    if(w->r->c==1)

    {

    w->l->c=1;

    w->c=0;

    rrotate(w);

    w=x->p->r;

    }

    w->c=x->p->c;

    x->p->c=1;

    w->r->c=1;

    lrotate(x->p);

    x=root;

    }

    }

    else

    {

    w=x->p->l;

    if(w->c==0)

  • 8/10/2019 Ada Lab File

    34/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    {

    w->c=1;

    x->p->c=0;

    rrotate(x->p);

    w=x->p->l;

    }

    if(w->r->c==1 && w->l->c==1)

    {

    w->c=0;

    x=x->p;

    }

    else

    {

    if(w->l->c==1)

    {

    w->r->c=1;

    w->c=0;

    lrotate(w);

    w=x->p->l;

    }

    w->c=x->p->c;

    x->p->c=1;

    w->l->c=1;

    rrotate(x->p);

    x=root;

    }

    }

    }

    x->c=1;

    }

    void del( node *t)

    {

    int x;

  • 8/10/2019 Ada Lab File

    35/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    coutx;

    if(t==nilt)

    {

    coutv)

    t=t->r;

    else if(xv)

    t=t->l;

    else

    break;

    }

    if(t==nilt)

    {

    coutl;

    }

    if(y->l!=nilt)

    z=y->l;

  • 8/10/2019 Ada Lab File

    36/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    else

    z=y->r;

    z->p=y->p;

    if(y->p==nilt)

    root=z;

    else if(y==y->p->l)

    y->p->l=z;

    else

    y->p->r=z;

    coutc==1)

    delfixup(z);

    }

    void search(node *t)

    {

    int x;

    coutx;

    if(t==nilt)

    {

    coutv)

    t=t->r;

    else if(xv)

    t=t->l;

  • 8/10/2019 Ada Lab File

    37/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    else

    break;

    }

    if(t==nilt)

    {

    cout

  • 8/10/2019 Ada Lab File

    38/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    int main()

    {

    int i,n;

    rbtree s;

    do

    {

    cout

  • 8/10/2019 Ada Lab File

    39/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    OUTPUT:

  • 8/10/2019 Ada Lab File

    40/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

  • 8/10/2019 Ada Lab File

    41/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    PROGRAM 8

    OBJECTIVE: PROGRAM TO IMPLEMENT BELLMAN-FORD ALGORITHM.

    ALGORITHM USED:

    procedure BellmanFord(list vertices, list edges, vertex source)

    // This implementation takes in a graph, represented as lists of vertices and edges,

    // and fills two arrays (distance and predecessor) with shortest-path information

    // Step 1: initialize graph

    for each vertex v in vertices:

    if v is source then distance[v] := 0

    else distance[v] := infinity

    predecessor[v] := null

    // Step 2: relax edges repeatedly

    for i from 1 to size(vertices)-1:

    for each edge (u, v) with weight w in edges:

    if distance[u] + w < distance[v]:

    distance[v] := distance[u] + w

    predecessor[v] := u

    // Step 3: check for negative-weight cycles

    for each edge (u, v) with weight w in edges:

    if distance[u] + w < distance[v]:

    error "Graph contains a negative-weight cycle"

    FUNCTIONALITY:

    The BellmanFord algorithm is analgorithm that computesshortest paths from a single

    sourcevertex to all of the other vertices in aweighted digraph.[1]It is slower than

    Dijkstra's algorithm for the same problem, but more versatile, as it is capable of handling

    graphs in which some of the edge weights are negative numbers. Negative edge weights

    are found in various applications of graphs, hence the usefulness of this algorithm.[2]If a

    graph contains a "negative cycle", i.e., acycle whose edges sum to a negative value, then

    there is no cheapestpath, because any path can be made cheaper by one morewalk

    through the negative cycle. In such a case, the BellmanFord algorithm can detect

    negative cycles and report their existence, but it cannot produce a correct "shortest path"

    answer if a negative cycle is reachable from the source.

    http://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Shortest_pathhttp://en.wikipedia.org/wiki/Vertex_%28graph_theory%29http://en.wikipedia.org/wiki/Weighted_digraphhttp://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-Bang-1http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-Bang-1http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-Bang-1http://en.wikipedia.org/wiki/Dijkstra%27s_algorithmhttp://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-FOOTNOTESedgewick2002-2http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-FOOTNOTESedgewick2002-2http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-FOOTNOTESedgewick2002-2http://en.wikipedia.org/wiki/Cycle_%28graph_theory%29http://en.wikipedia.org/wiki/Walk_%28graph_theory%29http://en.wikipedia.org/wiki/Walk_%28graph_theory%29http://en.wikipedia.org/wiki/Cycle_%28graph_theory%29http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-FOOTNOTESedgewick2002-2http://en.wikipedia.org/wiki/Dijkstra%27s_algorithmhttp://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm#cite_note-Bang-1http://en.wikipedia.org/wiki/Weighted_digraphhttp://en.wikipedia.org/wiki/Vertex_%28graph_theory%29http://en.wikipedia.org/wiki/Shortest_pathhttp://en.wikipedia.org/wiki/Algorithm
  • 8/10/2019 Ada Lab File

    42/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    C++ CODE IMPLEMENTATION:

    //PROGRAM TO IMPLEMENT BELLMAN-FORD ALGORITHM.

    #include

    #include

    #include

    #include

    using namespace std;

    class AdjListNode

    {

    int v;

    int weight;

    public:

    AdjListNode(int _v, int _w) { v = _v; weight = _w;}

    int getV() { return v; }

    int getWeight() { return weight; }

    };

    class Graph

    {

    int V; // No. of vertices'

    // Pointer to an array containing adjacency lists

    list *adj;

    public:

    Graph(int V); // Constructor

    // function to add an edge to graph

    void addEdge(int u, int v, int weight);

    void bell_ford(int src);

    };

    Graph::Graph(int V)

    {

    this->V = V;

    adj = new list[V];

    }

    void Graph::addEdge(int u, int v, int weight)

    {

    AdjListNode node(v, weight);

    adj[u].push_back(node); // Add v to u's list

    }

    void Graph::bell_ford(int src)

    {

    int dist[V];

    for (int i = 0; i < V; i++)

    dist[i] = INT_MAX;

    dist[src] = 0;

    for (int u = 0; u < V; u++)

  • 8/10/2019 Ada Lab File

    43/44

    NAME: NIREN BHARDWAJ, ROLL NO. 48

    {

    list::iterator i;

    if (dist[u] != INT_MAX)

    {

    for (i = adj[u].begin(); i != adj[u].end(); ++i)

    if (dist[i->getV()] > dist[u] + i->getWeight())

    {

    dist[i->getV()] = dist[u] + i->getWeight();

    }

    }

    }

    cout

  • 8/10/2019 Ada Lab File

    44/44

    OUTPUT: