ada lab progs

Upload: kanth10

Post on 03-Apr-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Ada Lab Progs

    1/80

    Algorithm for Linear Search

    Algorithm linear_search (A, i , n)//Purpose : search for an item in an array A[0..n-1] using linear search.

    //Input: keythe element to be searched

    // A[0..n-1]the list of elements where the searching takes place.// nnumber of elements in the list.//Output: Position is returned if search is successful otherwise,1 is returned

    {

    if i>nreturn -1

    else

    if A[i] keyreturn i

    elselinear_search(A,++i,n)

    }

    Time complexity of Linear Search is (n)

    Algorithm for Binary Search

    Algorithm binary_search( A, low, high)

    //Purpose : search for an item in an array A[0..n-1] using binary search.

    //Input: keythe element to be searched// A[0..n-1]the list of elements where the searching takes place.

    // nnumber of elements in the list.

    //Output: Position is returned if search is successful otherwise,1 is returned{

    low 0

    high 1

    if low > high

    return -1

    mid (low+high)/2

    if a[mid] key

    return mid

    if a[mid] > key

    binary_search(A,low,mid-1)

    elsebinary_search(A,mid+1,high)

    }

    Time complexity of Binary Search in Best case is (1)Time complexity of Binary Search in Worst case is (log2 n)

    Time complexity of Binary Search Average case is (n2)

  • 7/29/2019 Ada Lab Progs

    2/80

    /*1) Perform recursive binary search and linear search. Hence find the time required to

    search an element.*/

    #include

    #include

    #include#include //Inclusion of header files

    int n,i=0;

    int a[20]; //Global declaration

    //Function to perform binary search

    int bin_search(int a[],int key, int low,int high)

    {int mid;

    mid=(low+high)/2; //Finding the mid element

    if(low>high) //Termination condition{

    return -1;

    }

    if(a[mid]==key){

    return mid; //If mid is the key return mid

    }if(key

  • 7/29/2019 Ada Lab Progs

    3/80

    coutn;

    cout

  • 7/29/2019 Ada Lab Progs

    4/80

    break;

    default:cout

  • 7/29/2019 Ada Lab Progs

    5/80

    Algorithm for Heapsort

    Algorithm heapsort (A , n)// Purpose: Sort the list in ascending order.

    // Input: A[0..n-1]the list to be sorted

    // nthe total number of elements.//Output:A[0..n-1]the sorted list{

    call heapify(A , n)

    for (i n to 2 by -1 do ){

    t A[i]

    A[i] A[i]

    A[i] t

    adjust(A,1,i-1)

    }

    }

    //This algorithm readjust the elements in the array and to form a heap

    Algorithm heapify (A, n)// Purpose: to create a max heap so that item at the root is the highest and given any node,

    // the item at that node is greater than the item at left child and right child

    // Input: A[0..n-1]the items to be inserted into the heap

    // nthe number of items to be inserted into the heap.//Output:A[0..n-1]the contains the max heap

    {for i n/2 to 1 by -1 do

    {call adjust (A, i ,n)

    }

    }

  • 7/29/2019 Ada Lab Progs

    6/80

    Algorithm adjust( A, i ,n)

    // Purpose: to create a max heap so that item at the root is the highest and given any node,

    // the item at that node is greater than the item at left child and right child// Input: A[0..n-1]the items to be inserted into the heap

    // nthe number of items to be inserted into the heap.

    //Output:A[0..n-1]the contains the max heap{

    j 2*i

    item A[i]

    while(j < = n) do

    {

    if (j < n ) and A[j] < A[j+1])

    j j+1if item > = A[j]

    then breakelse

    {A[j] A[j/2]

    j 2*j}

    }

    A[j/2] item

    }

    Time complexity of Heap Sort is (n log2 n)

  • 7/29/2019 Ada Lab Progs

    7/80

    /* 2) Sort a given set of elements using Heapsort method.*/

    #include#include

    #include

    template //Creating a templatevoid heapify(T a[],int n)

    {

    int i,j,k;T item;

    for(k=1;k0 && item>a[j]){ //while parent exist & item>parenta[i]=a[j]; //move parent down to childi=j; //make parent as child

    j=(i-1)/2; //obtain new parent for child}

    a[i]=item; //Insert item into childs position

    }}

    template

    void adjust(X a[],int n){

    int i=0,j;

    X item;j=0;

    item=a[j];

    i=2*j+1;

    while(i

  • 7/29/2019 Ada Lab Progs

    8/80

    }

    a[j]=item; //Insert item to parent pos}

    templatevoid heapsort(U a[],int n){

    int i;

    U temp;heapify(a,n); //calling the heapify functionfor(i=n-1;i>0;i--)

    {

    temp=a[0]; //swapping the root nodea[0]=a[i];

    a[i]=temp;

    adjust(a,i);}

    }

    templatevoid disp(D a[],int n)

    {

    cout

  • 7/29/2019 Ada Lab Progs

    9/80

    case 1:

    coutsort characters

    1Enter the elements

    3

    8

    16

    9

    3The sorted array is :

  • 7/29/2019 Ada Lab Progs

    10/80

    1

    3

    36

    8

    91->sort integers2->sort doubles

    3->sort characters

    2Enter the elements

    5.66

    7.3

    8.662.22

    9.88

    1.0The sorted array is :

    1

    5.66

    2.227.3

    8.66

    9.881->sort integers

    2->sort doubles

    3->sort characters

    3Enter the elements

    c

    om

    p

    a

    qThe sorted array is :

    a

    mc

    o

    p

    q1->sort integers

    2->sort doubles

    3->sort characters4 */

  • 7/29/2019 Ada Lab Progs

    11/80

    Algorithm for Merge Sort

    //This algorithm sorts the element taking high and low.

    Algorithm merge_sort(low, high)

    // Purpose: Sort the list in ascending order.// Input: A[0..n-1]the list to be sorted// nthe total number of elements.

    //Output:A[0..n-1]the sorted list

    {if low < high

    {

    mid (low + high)/2merge_sort(low,mid)

    merge_sort(mid+1,high)merge(low,mid,high)

    }}

    Algorithm merge (low, mid, high)

    // Purpose: Merge two sorted arrays where the first array starts from low to mid and the secondsstarts form mid + 1 to high.

    // Input: A[0..n-1]is sorted from the index position low to mid.

    // A[0..n-1]is sorted from the index position mid + 1 to high.

    // nthe total number of elements.//Output:A[0..n-1]the sorted from index low to high.

    {

    h lowi low

    j mid+1

    while(h < = mid and j < = high)

    {

    if A[h] < = A[j] then B[i] A[h]

    h h+1else

    B[i] A[j]

    j j+1

    }

  • 7/29/2019 Ada Lab Progs

    12/80

    if (h > mid) then

    {

    for (k j to high) do

    B[i] A[k]

    j i+1

    }

    else{

    for k h to mid do

    B[i] A[k]

    j i+1\

    }

    for (k low to high) do

    A[k] B[k]}

    Time complexity of Merge Sort (n log2 n)

  • 7/29/2019 Ada Lab Progs

    13/80

    /* 3.a) Sort a given set of elements using Mergesort method.*/

    #include#include

    void merge(int a[],int low,int mid,int high){int i,j,k,c[20];

    k=low;

    i=low;j=mid+1;

    while((i

  • 7/29/2019 Ada Lab Progs

    14/80

    cout

  • 7/29/2019 Ada Lab Progs

    15/80

    Algorithm to check whether a given graph is connected or not using Depth First Search

    Algorithm test connected( )//Purpose: To check whether given graph is connected or not using DFS

    //Input: A[][]adjacency matrix of the given graph

    nnumber of nodes in the graphvfrom where the traversal is to be initiatedreach[] - indicate the vertices that are visited and that are not visited.

    //Output: The graph is connected or not connected

    {read v

    dfs(v)

    for i 1 to n do{

    if(reach[i]!=1){

    Print not ConnectedExit(0);}

    print Connected

    }}

    void dfs(v){

    reach[v] 1

    for i 1 to n do{if (A[v][i])

    {

    if(!reach[i])dfs(i)

    }

    }

    }

    Time complexity of DFS is ( |V

    2

    | )

  • 7/29/2019 Ada Lab Progs

    16/80

    /* 3. b)Check whether a given graph is connected or not using DFS method.*/

    #include

    #include

    class graph //Class declaration{

    private : int a[20][20],reach[10];

    int n;

    public: void read()

    {

    coutn;

    cout

  • 7/29/2019 Ada Lab Progs

    17/80

    for(int i=0;i

  • 7/29/2019 Ada Lab Progs

    18/80

    Algorithm for Selection Sort

    Algorithm selection_sort (A[0..n-1])// Purpose: Sort the list in ascending order.

    // Input: A[0..n-1]the list to be sorted

    // nthe total number of elements.//Output:A[0..n-1]the sorted list{

    for i 0 to n-2 do{

    min i;

    for j i+1 to n-1 do{

    if A[j]

  • 7/29/2019 Ada Lab Progs

    19/80

    /*4) Sort a given set of element using selection sort and hence find time required to sort

    element */

    #include

    #include

    #include#include

    template

    void sel(T a[],int n){

    int min;

    T temp;

    for(int i=0;i

  • 7/29/2019 Ada Lab Progs

    20/80

    cout

  • 7/29/2019 Ada Lab Progs

    21/80

    /* OUTPUT

    Enter the Number of elements

    61->Sort integers

    2->Sort doubles

    3->Sort characters1Enter the elements

    4

    61

    8

    2

    9The sorted array is :

    1

    24

    6

    8

    9Time taken for sorting : 5.8667e-06

    1->Sort integers

    2->Sort doubles3->Sort characters

    2

    Enter the elements

    2.32.4

    1.2

    7.76.5

    9.2

    The sorted array is :

    1.22.3

    2.4

    6.57.7

    9.2

    Time taken for sorting : 1.6762e-05

    1->Sort integers2->Sort doubles

    3->Sort characters

    3Enter the elements

  • 7/29/2019 Ada Lab Progs

    22/80

    c

    o

    mp

    a

    qThe sorted array is :a

    c

    mo

    p

    q

    Time taken for sorting : 4.1905e-061->Sort integers

    2->Sort doubles

    3->Sort characters0

    */

  • 7/29/2019 Ada Lab Progs

    23/80

    Algorithm for Topological Ordering

    Topological_Order ( )//Purpose: To obtain the sequence of jobs to be executed resulting in Topological order.

    //Input: A- adjacency matrix of the given graph.

    n- the no. of vertices in the graph.//Output: v-indicates the jobs that are to be executed in the order.{

    stack s

    for i 0 to n do{

    for (int j 1 to n do)if (A[i][j] )

    + + indegree[j]

    }

    for i 1 to n do

    {if (indegree[i]= = 0)

    {s.push(i)

    reach[i] 1

    }}

    while (!s.empty ( ))

    {

    temp s.pop( )

    v[++ count] tempfor j 1 to n do{

    if (A[temp][j]){

    if(!reach[j])

    reach[j] 1

    indegree[j]if(!indegree[j])

    s.push( j )

    }

    }}

    Time complexity of Topological Order is ( |V2| )

  • 7/29/2019 Ada Lab Progs

    24/80

    /* 5.a) Obtain the Topological ordering of vertices in a digraph.*/

    #include#include

    #define MAX 5

    class stack //Declaration of class stack{

    Private :int a[MAX], top;

    public:

    stack();

    void push(int); //Basic stack functions

    int pop();int empty();

    };

    stack::stack()

    {

    for(int i=0;i

  • 7/29/2019 Ada Lab Progs

    25/80

    temp=a[top];

    top--;

    }return temp; //Returns the popped element}

    int stack::empty(){

    if(top==-1)

    return 1;else

    return 0;

    }

    void topological() //Function for topological sort

    {

    stack s;int a[30][30],temp, i, j;

    int count=0,v[30],reach[30],indegree[30],n;

    cout

  • 7/29/2019 Ada Lab Progs

    26/80

    {

    temp=s.pop(); //Pop an element from stack

    v[++count]=temp; //assign temp to vfor(j=1;j

  • 7/29/2019 Ada Lab Progs

    27/80

    Algorithm for Insertion Sort

    Algorithm insertion_sort (A[0..n-1])

    // Purpose: Sort the list in ascending order.// Input: A[0..n-1]the list to be sorted// nthe total number of elements.

    //Output:A[0..n-1]the sorted list

    {

    for j 0 to n-1{

    item A[i]

    j i-1while(j > = 0 and item < A[j]){

    A[j+1] A[j]j j - 1

    }

    A[j+1] item

    }

    }

    Time complexity of Insertion Sort in Best case is (n)Time complexity of Insertion Sort in Worst case is O(n

    2)

    Time complexity of Insertion Sort in Average case is (n2)

  • 7/29/2019 Ada Lab Progs

    28/80

    /* 5. b)Sort a given set of elements using Insertion sort method.*/

    #include#include

    void insert_sort(int a[],int n){int i,j,item;

    for(i=0;i=0 && item

  • 7/29/2019 Ada Lab Progs

    29/80

    Algorithm for Knapsack Problem

    Algorithm Knapsack / ele,rem_cap, reach[ ])//Purpose: to solve knapsack problem using dynamic programming.

    //Input: nthe no. of objects to be selected.

    m- the capacity of the knapsackw- weights of all the objects.pprofits of all the objects.

    //Output: the optimal solution for the no. of objects selected with specified remaining capacity.

    if ( ele num-1)if (amount[ele] rem_cap )

    return (rec(ele +1, rem+cap,reach))reach1[10]

    for i 0 to num

    reach1[i] reach[i]

    reach1[ele] 1

    a rec(ele+1,rem_cap-amount[ele],reacb1) + prof[ele]

    b rec(ele+1,rem_cap,reach)if max(a,b)

    for i 0 to num

    reach[i] reach1[i]return a

    return b

    Time complexity of Knapsack Problem is (mn)

  • 7/29/2019 Ada Lab Progs

    30/80

    /* 6) Implement 0/1 Knapsack problem using dynamic programming.*/

    #include #include

    #include

    class knapsack{

    private: int profits[30];

    int weights[30]; //v->Optimal solution matrixint n,m,v[30][30]; //m->capacity,n->no.of elements

    public:

    getdata()

    {coutn;

    cout

  • 7/29/2019 Ada Lab Progs

    31/80

    }

    int max1(int a,int b){

    if(a>b)

    return a;elsereturn b;

    }

    void display()

    {

    int optsoln; //stores the optimal solution

    optsoln = mfk(n,m);int a=n;

    int b=m;

    cout0{

    if(v[a][b]!=v[a-1][b]) //if v[i][j]!=v[i-1][j]

    {cout

  • 7/29/2019 Ada Lab Progs

    32/80

    /*

    OUTPUT :

    Enter the no of objects: 5Enter the weights:

    3 9 1 5 2

    Enter the profits :56 34 2 56 43Enter the knapsack capacity: 10

    { 5 4 1 }

    Optimal solution = 155

    Enter the no of objects: 4

    Enter the weights:2 1 3 2

    Enter the profits :

    12 10 20 15Enter the knapsack capacity: 5

    { 4 2 1 }

    Optimal solution = 37

    */

  • 7/29/2019 Ada Lab Progs

    33/80

    Dijkstras Algorithm

    Algorithm Dijkstra (G)//Purpose: To find the shortest path from the starting vertex to other vertices.

    //Input: A weighted connected graph G=

    //Output: The length of shortest path from starting vertex to other vertices.{

    for i 1 to n

    s[i] 0

    dist[i] cost[v][i]

    s[v] 1

    dist[v] 0

    num 2while ( num < = n)

    u choose( )

    s[u] 1

    num++for i w to nif (((dist[u] + cost[u][w]) < dist[w] ) && (!s[w]))

    dist [w]=dist [u] + cost [u][w]

    }

    //Algorithm to choose the nearest non selected vertex from a particular vertex

    Algorithm choose ( )

    {

    j 1

    min 1000

    for (dist[w] < min) &&(!s[w]))min dist[w]

    j wreturn ( j )

    }

    Time complexity of Dijkstras Algorithm is (E log V)

  • 7/29/2019 Ada Lab Progs

    34/80

    /* 7) From a given weighted connected graph, find the shortest paths to other vertices,

    using Dijkstras algorithm.*/

    #include

    #include

    class dijkstras{

    public:int n,v,dist[10],cost[10][10];

    void read();

    void shortest_path(int v,int cost[10][10],int dist[10],int n);

    int choose(int dist[10],int s[10],int n);void disp();

    };

    void dijkstras::read()

    {

    int i,j;cout

  • 7/29/2019 Ada Lab Progs

    35/80

    {

    int u=choose(dist,s,n); //choose a vertex which is

    //nearer to vs[u]=1; //mark it as visitednum++;

    for(int w=1;wcurrent edge length

    //cost[u][w]->edge length from u to other vertices

    //dist[w]->w indexes dist which gives the distance

    //from the first vertexif(dist[u]+cost[u][w]

  • 7/29/2019 Ada Lab Progs

    36/80

    void main()

    {dijkstras d;

    clrscr();

    d.read();d.shortest_path(d.v,d.cost,d.dist,d.n);d.disp();

    getch();

    }

    /*

    OUTPUT :

    Enter the no of vertices4

    Enter the cost of adjacency matrix

    0 10 15 255 0 2 1000

    1000 1000 0 13

    10 1000 1000 0

    Enter the starting vertex1

    Node 2 is at the distance of : 10 from 1

    Node 3 is at the distance of : 12 from 1Node 4 is at the distance of : 25 from 1

    */

  • 7/29/2019 Ada Lab Progs

    37/80

    Algorithm for Quick SortAlgorithm partition(m, p)

    // Purpose: Partition the array into two parts such that elements towards left of the key elementare less than the key element and the elements towards right of the key element

    are greater than the key element.

    // Input: A[0..n-1]is a unsorted from the index position low to high.//Output: A[0..n-1]is divided into two parts as told above.{

    A[m],A[m+1],..A[p-1])

    v A[m] //pivot element

    i m

    do{

    do

    {

    i i+1

    }while(A[i] > = v)do

    {

    p p-1

    }while(A[p]< = v)

    if i < pswap (A[i],A[p])

    else

    break

    }while(1)

    A[m] A[p]

    A[p] vreturn p

    }Algorithm quick_sort(p,q)

    // Purpose: Sort the elements of the array between the lower bound and upper bound.

    // Input: A[0..n-1]the list to be sorted with low and high as lower bound and upper bound

    // nthe total number of elements.//Output:A[0..n-1]the sorted list

    {

    A[n+1]if(p < q)

    then j q+1partition (p,j)

    quick_sort(p,j-1)

    quick_sort(j+1,q)}

    Time complexity of Quick Sort in Best case is (n log2 n)

    Time complexity of Quick Sort in Worst case is O(n2)

    Time complexity of Quick Sort in Average case is (n log2 n)

  • 7/29/2019 Ada Lab Progs

    38/80

    /* 8) Sort a given set of elements using Quicksort method.*/

    #include#include

    #include //Inclusion of header files

    template //Template functionint partition(T a[],int low,int high)

    {

    int i=low+1,j=high;T temp;

    while(1)

    {

    while(ia[i])i++;while(a[low]

  • 7/29/2019 Ada Lab Progs

    39/80

    template //Display template functionvoid disp(D a[],int n)

    {cout

  • 7/29/2019 Ada Lab Progs

    40/80

    default:exit(0);

    break;

    }}

    getch();

    }

    /*

    OUTPUT :enter the number of elements

    6

    1->sort integers2->sort doubles

    3->sort characters

    1Enter the elements

    3

    2

    41

    6

    5The sorted array is :

    1

    2

    34

    5

    61->sort integers

    2->sort doubles

    3->sort characters

    2Enter the elements

    2.1

    3.51.2

    5.2

    6.2

    4.4The sorted array is :

    1.2

    2.13.5

  • 7/29/2019 Ada Lab Progs

    41/80

    4.4

    5.2

    6.21->sort integers

    2->sort doubles

    3->sort characters3Enter the elements

    c

    om

    p

    a

    qThe sorted array is :

    a

    cm

    o

    p

    q1->sort integers

    2->sort doubles

    3->sort characters0

    */

  • 7/29/2019 Ada Lab Progs

    42/80

    Kruskals Algorithm

    Algorithm Kruskal(G)

    //Kruskals Algorithm for constructing a minimum spanning tree.//Input: A weighted connected graph G=( V,E)

    //Output: ET, the set of edges composing a minimum spanning tree of G

    Sort E in non-decreasing order of the edge weights

    W(ei1) W( ei |E|)

    ET ; //initialize the set of tree edges

    ecounter 0 //inititalize the size of tree

    k 0 //initialize the no of processed edges

    while ecounter < |V| -1

    k k + 1if ET U{eik} is a cyclic

    ET ET U{eik}Ecounter ecounter + 1

    return ET

    With an efficient sorting algorithm the

    Time complexity of Kruskals Algorithm is O( |E| log |E| )

  • 7/29/2019 Ada Lab Progs

    43/80

    /* 9) Find minimum cost spanning tree of a given undirected graph using Kruskal's

    algorithm*/

    #include

    #include

    #define max 10

    struct ec //structure to store each edge

    {

    int weight,u,v;};

    class kruskal //class kruskal declaration

    {private:int e,n,cost[max][max],parent[10];

    struct ec edge[max*max];

    public: //member functionsvoid getdata();

    void stree();

    void minheapcreate();

    struct ec minheapdelete();void adjust(int i,int g);

    int find(int i);

    void uniont(int i,int j);};

    void kruskal::getdata() //input function

    {e=1;

    cout

  • 7/29/2019 Ada Lab Progs

    44/80

    }

    }

    }

    void kruskal::stree()

    {int mincost=0,i=0,T[max][2],ne=0;struct ec temp;

    for(int s=1;s

  • 7/29/2019 Ada Lab Progs

    45/80

    {

    int k=i;

    int j=k*2;struct ec item;

    item.u=edge[i].u;

    item.v=edge[i].v;item.weight=edge[i].weight;while(j

  • 7/29/2019 Ada Lab Progs

    46/80

    int kruskal::find(int i) //find parent node

    {

    while(parent[i])i=parent[i];

    return i;

    }

    void kruskal::uniont(int i,int j) //joins an edge to tree

    {

    parent[j]=i;}

    void main() //begin of main

    {kruskal k;

    clrscr();

    k.getdata();k.stree();

    getch();

    } //end of main/* OUTPUT :

    RUN1:

    Enter the number of vertices:6Enter the weighted adjacancy matrix:0 10 1000 1000 11 100010 0 10 1000 8 9

    1000 10 0 1000 1000 5

    1000 1000 1000 0 12 711 8 1000 12 0 71000 9 5 7 7 1000Minimum cost = 37

    6--->36--->4

    6--->55--->2

    2--->1

    RUN2:

    Enter the number of vertices:

    4

    Enter the weighted adjacancy matrix:1000 40 60 1040 1000 10 2060 10 1000 30

    10 20 30 1000Minimum cost = 404--->13--->24--->2 */

  • 7/29/2019 Ada Lab Progs

    47/80

    Algorithm for Breath First Search

    Algorithm BFS ( )//Purpose: Traverse the graph form the given source node.

    //Input: A[][]adjacency matrix of the given graphnnumber of nodes in the graphvfrom where the traversal is to be initiated

    reach [ ]- indicate the vertices that are visited and that are not visited.

    //Output: the vertices, which are reachable and not reachable from the source node

    {

    read v

    print Vertices reachable are

    insert (v)

    reach[v] 1

    while (! Empty ( )){

    int n delete( )

    for j 1 to n do

    {

    if (A[u][j]){

    if (!reach[j])

    {

    reach[j] 1insert (j)

    print j}

    }}

    }

    }

    Time complexity of BFS is ( |V2| )

  • 7/29/2019 Ada Lab Progs

    48/80

    /* 10.a)Print all the nodes reachable from a given starting node in a digraph using BFS

    method.*/#include#include

    #include

    #include

    const int max=20;

    int a[20][20], reach[20], n; //Global declaration

    class QUEUE //declaration of class queue

    {

    Private : int q[max];

    int f,r;public:

    QUEUE();

    void insert(int x);int del();

    int empty();

    void bfs();

    };

    QUEUE::QUEUE()

    {f=0; //Initialize front and rear=0r=-1;

    }

    void QUEUE::insert(int x)

    {

    if(r==max-1)cout

  • 7/29/2019 Ada Lab Progs

    49/80

    else

    {

    a=q[f++];return a;

    }

    }

    int QUEUE::empty()

    {

    if(f>r) //If front>rear then reset f,r{

    f=0;

    r=-1;

    }if(r==-1)

    return 1;

    elsereturn 0;

    }

    void QUEUE:: bfs(){

    int v;

    coutv;

    insert(v); //Initialize a queue with vreach[v]=1; //Mark v as reached

    cout

  • 7/29/2019 Ada Lab Progs

    50/80

    void main()

    {QUEUE B;

    int i, j;

    clrscr();coutn;

    cout

  • 7/29/2019 Ada Lab Progs

    51/80

    Floyds Algorithm

    Algorithm Floyd (W[1n, 1.n])

    //Purpose: Implements Floyds algorithm for the all pairs shortest paths problem.

    //Input: The weight matrix W of a graph.

    //Output : The distance matrix of the shortest paths length.D = W // is not necessary if W can be overwritten

    for k 1 to n do

    for i 1 to n do

    for j 1 to n do

    D[i,j] min {D [i,j], D[i,k]+D[k,j]}

    return D

    Time complexity of Floyds Algorithm is ( n3

    )

  • 7/29/2019 Ada Lab Progs

    52/80

    /* 10.b) Implement all pairs shortest paths of the problem using FLOYD'S

    ALGORITHM.*/

    #include //Header Files#include

    #include#include#include

    class floyd{ //a->adjacency matrix,r->resultant matrixprivate : int a[20][20],r[20][20],n;

    public:

    floyd(){

    n=0;

    }int cal(int,int,int);

    void read();

    void disp();

    int min(int,int);void shortest();

    };

    void floyd::read()

    {

    int i,j;

    coutn;

    cout

  • 7/29/2019 Ada Lab Progs

    53/80

    int floyd::min(int x,int y) //Function to calculate{ //minimum of 2 pathsif(x

  • 7/29/2019 Ada Lab Progs

    54/80

    7 7 0 16 16 9 0 */

    Algorithm for Sum of SUBSET

    Algorithm Sum of Sub (s, k, r)

    // Purpose: To find sum of subset is equal to given value

    //Input: sis a given setdis sum of subset

    //Output: getting the subsets whose sum value is equal to d.

    {

    if k < = n

    x[k] 1

    if s + w[k] d

    {

    p++

    print solution vector is

    for j 1 to nprint x[j]

    }else

    if (s + w[k] + w [k+1]

  • 7/29/2019 Ada Lab Progs

    55/80

    *11) Find the subset of the given set S={S1,S2,.....,Sn} of n positive integer whose sum is

    equal to the given positive integer,a suitable message is to be displayed if the given problem

    instance have no solution.*/

    #include //Header Files#include

    #include

    #include#include

    int p=0;

    class subset{

    private: int x[20],w[20]; //x[]->Flag array to indicate

    int d,n; //element is selected.//w[]->Set of weighted elementspublic: //d->Subset generation constraint

    subset(); //(max weight allowed in subset)

    //number of elements in the setvoid sumofsub()

    {

    sumofsub(0,1,d);}

    void sumofsub(int,int,int);

    void read();

    };

    //constructor

    subset::subset(){

    int i;

    coutn;cout

  • 7/29/2019 Ada Lab Progs

    56/80

    p++; //count to indicate any subset generatedcout

  • 7/29/2019 Ada Lab Progs

    57/80

    { 5 12 13 }{ 8 10 12 } */

    Horspools Algorithm

    Algorithm shift table(p[0m-1])

    //Purpose: fills the shift table used by Horspools algorithm

    //Input: Pattern p[0.m-1] and an alphabet of possible characters.//Output: Table [0size-1] indexed by the alphabets

    //Characters and filled with shift sizes computed by formula

    Initialize all the elements of length with m

    For j 0 to m-2 do Table [p[j]] = m-1-jReturn Table

    Algorithm Horspool Matching[p[0m-1], T[0n-1])

    //purpose: Implements Horspools algorithm for string matching//Input: The index of the left end of the first matching substring or1 if there are no matches.

    Shift table(p[0.m-1]) // generate Table of shifts

    i m-1 // position of the patterns right end

    while i

  • 7/29/2019 Ada Lab Progs

    58/80

    /* 12.a) Implement Horspool algorithm for string matching. */

    #include#include

    #include

    #include

    class HORSPOOL

    {

    private:int m,n; //p ->Substring, s-> Textchar p[30],s[50],T[50]; //T-> Shift Table

    public:

    void get() //M.F to scan string and substring{

    cout

  • 7/29/2019 Ada Lab Progs

    59/80

    int index;

    m=strlen(p); //String length of substringn=strlen(s); //String length of textshift_table();

    int i=m-1; //initialize I to m-1 i.e, last

    //but one character of substringwhile(i

  • 7/29/2019 Ada Lab Progs

    60/80

    Algorithm to compute Binomial Co-efficient

    Algorithm Binominal (n,k)//Purpose: Computes c(n,k) by the dynamic programming algorithm.

    //Input : a pair of non negative integers n >= k>=0

    //Output : The value of c(n,k)for i 0 to n do

    for j 0 to min(i,k) doif ( j=0 || j=k)

    c[i , j] 1else

    c[i , j]=c[i-1,j-1] + c[i-1,j]return c[n , k]

    Time complexity of Binomial Co-efficient is ( nk )

  • 7/29/2019 Ada Lab Progs

    61/80

    /*12.b) Find The Binomial Co-Efficient Using Dynamic Programming*/

    #include //Header Files#include

    #include

    #include#includeclass BINOMIAL

    {

    private : int n,k;public :

    void read()

    {

    coutn;

    coutk;}

    int min(int a,int b)

    {

    return a

  • 7/29/2019 Ada Lab Progs

    62/80

    /*int min(int n,int m)

    {

    return((n

  • 7/29/2019 Ada Lab Progs

    63/80

    Prims Algorithm

    Algorithm PRIM(G)

    //Purpose: Prims algorithm for constructing a minimum spanning tree

    //Input: A weighted connected graph G = (V,E)

    //Output: ET, the set of edges composing a minimum spanning tree of G

    VT { V0} // the set of tree vertices can be initialized with any vertex.

    ET

    For i 1 to |V| -1 do//find a minimum weight edge e* (V*,U*)

    //among all the edges (V,U) such that V in VT and U is in V-VT

    VT VT U {U*}

    ET ET U {e*}return ET

    Time complexity of Prims Algorithm is ( |V2

    | )

  • 7/29/2019 Ada Lab Progs

    64/80

    /* 13) Find minimal cost spanning tree of a given undirected graph using prims

    algorithm.*/

    #include

    #include //Header file

    #include

    const int max=20; //declaration of constantconst int ne=1000; //ne->indicates no edge

    //Definition of the graph

    class graph

    {

    private: //private data member

    int a[max][max],n; //adjacency matrixint reach[max]; //Array to check whether i is

    // included n the spanning treeint close[max]; //Taken to find a vertex which

    // is having mincost edge from iint r[2][max]; //Array containing spanning tree

    public:

    graph();

    void read();

    void disp();void prim();

    };

    graph::graph() //constructor

    {

    int i;

    for(i=0;i

  • 7/29/2019 Ada Lab Progs

    65/80

    cin>>a[i][j];

    }

    void graph::disp() //Function to display the matrix

    {int i,j;cout

  • 7/29/2019 Ada Lab Progs

    66/80

    for(j=1;j

  • 7/29/2019 Ada Lab Progs

    67/80

    g.prim();

    getch();

    }

    /*

    OUTPUT:

    ENTER THE GRAPH

    ENTER THE TOTAL NUMBER OF VERTICES IN THE GRAPH

    4ENTER THE ADJACENCY MATRIX OF THE GRAPH

    1000 1 5 3

    1 1000 1000 1000

    5 1000 1000 23 1000 2 1000

    THE ADJACENCY MATRIX IS

    1000 1 5 31 1000 10000 1000

    5 1000 1000 2

    3 1000 2 10000

    THE VERTICES IN THE SPANING TREE ARE1--2

    4--1

    3--4THE TOTAL COST OF THE SPANING TREEE IS 6

    2nd

    RUN:

    ENTER THE GRAPH

    ENTER THE TOTAL NUMBER OF VERTICES IN THE GRAPH4

    ENTER THE ADJACENCY MATRIX OF THE GRAPH

    1000 1000 10 301000 1000 1000 1000

    10 1000 1000 20

    30 1000 20 1000

    THE ADJACENCY MATRIX IS1000 1000 10 30

    1000 1000 1000 1000

    10 1000 1000 2030 1000 20 1000

    THE GRAPH IS DISCONECTED

    */

  • 7/29/2019 Ada Lab Progs

    68/80

    To print the reachable nodes using Depth First Search

    Algorithm test connected ( )//Purpose: Traverse the graph form the given source node.

    //Input: A[][]adjacency matrix of the given graph

    nnumber of nodes in the graphvfrom where the traversal is to be initiatedreach [ ]- indicate the vertices that are visited and that are not visited.

    //Output: the vertices, which are reachable and not reachable from the source node

    {print Enter the starting vertex

    read V

    dfs(V)

    }

    Algorithm dfs(V)

    { reach[V] 1cout>>V

    for i 1 to n do

    {if(A[V][i])

    {

    if(!reach[i])

    dfs(i)}

    }

    }

    Time complexity of DFS is ( |V2| )

  • 7/29/2019 Ada Lab Progs

    69/80

    /* 14.a)Print All Nodes Reachable From A Given Starting Nodes In A

    Given Digraph Using Depth First Search Method*/

    #include

    #include //Header file

    #include

    class graph //defination of the class{

    private: //data memeber

    int a[20][20],reach[20],n;

    public: //member function

    void intialise();void read();

    void disp();

    void testcondition();

    void DFS(int v);

    };

    //Function to initialize reach

    void graph::intialise()

    {for(int i=0;i

  • 7/29/2019 Ada Lab Progs

    70/80

    //Function to display the matrix

    void graph::disp(){

    int i,j;

    cout

  • 7/29/2019 Ada Lab Progs

    71/80

    /**********MAIN FUNCTION**********/

    main(){

    clrscr();

    int p;graph G;G.read();

    G.testcondition();

    G.disp();getch();

    return(0);

    }

    /* OUTPUT:

    Enter the total number of vertices

    4

    Enter the adjacency matrix of the digraph

    0 1 0 1 0 0 0 0 1 0 0 0 0 1 1 0

    The vertices reachable from 1 are: 2 4 3

    The vertices reachable from 2 are:

    The vertices reachable from 3 are: 1 2 4The vertices reachable from 4 are: 2 3 1

    The adjacency matrix of the given digraph is

    0 1 0 1

    0 0 0 01 0 0 0

    0 1 1 0

    Enter the total number of vertces

    3

    Enter the adjacency matrix of the digraph

    0 1 1 0 0 1 0 0 0

    The vertices reachable from 1 are: 2 3

    The vertices reachable from 2 are: 3

    The vertices reachable from 3 are:

    The adjacency matrix of the given digraph is0 1 1

    0 0 1

    0 0 0 */

  • 7/29/2019 Ada Lab Progs

    72/80

    Warshalls Algorithm

    Algorithm warshall ( A[1n,1..n])

    //Purpose: Implements warshalls algorithm for computing the transitive closure//Input: the adjacency matrix A of a diagraph with n vertices.

    //Output: The transitive closure of the diagraph

    R(0)

    A

    for k 1 to n do

    for i 1 to n do

    for j 1 to n do

    R(k)

    [i , j ] R(k-1)

    [i , j ] or R(k-1)

    [i , k] and R(k-1)

    [k , j]return R

    (n)

    Time complexity of Warshalls Algorithm is ( n3

    )

  • 7/29/2019 Ada Lab Progs

    73/80

    /*14.b) Compute the transitive closure of a given directed

    graph using washalls algorithm. */

    #include //HEADER FILES#include

    #include#include#include

    class warshal{

    private : int a[20][20],r[20][20][20],n;

    //a[][]->adjacency matrix

    //r[][][]->resultant matrixpublic:

    warshal()

    {n=0;

    }

    void cal();void read();

    };

    void warshal::read()

    {

    int i,j;

    coutn;

    cout

  • 7/29/2019 Ada Lab Progs

    74/80

    //r[k-1][i][j]->intermediate vertices numbered not more than k-1

    //2nd

    condition if intermediate vertices numbered not more than k-1

    //from r[i][k] to k and k to r[k][j].

    cout

  • 7/29/2019 Ada Lab Progs

    75/80

    Queens Problem

    Algorithm Camplace (int k, int i)//Purpose: To place the Queen on Chess board (Such that, no two queens are placed in same row,

    //same column and diagonal.

    //Input: n - Numbers of Queens//Output: Solution Queens are placed on Chess board.{

    for j 1 to k do{

    if ((x[j] = i) || ((fabs (x[j]-i))) == (fabs (jk)))return false

    }

    return true;

    }

    Algorithm n_queens (int k){

    for i 1 to n do

    {

    if(complace (k , i)){

    x[k]=i;

    if(k = = n)

    {display( );

    }

    else n_queens(k+1);}

    }

    }

    Algorithm display( )

    {

    for i 1 to n do{

    for j 1 to n do

    { if (j = x[i])

    board [i][j] 0else

    board[i][j] *

    }}

  • 7/29/2019 Ada Lab Progs

    76/80

    for i 1 to n do

    for j 1 to n do{

    print board[i][j];}

    exit(1);}

    }}

    Time complexity of Queens Algorithm is (nk)

  • 7/29/2019 Ada Lab Progs

    77/80

    /* 15) Implement N Queen's problem using Back Tracking.*/

    #include#include

    #include

    #include

    int n;

    class queen //class declaration{

    private : int x[20]; //datachar board[10][10];

    public :

    int canplace(int,int); //member functions

    void nQueens(int);void display();

    };

    int queen::canplace(int k,int i){

    for(int j=1;jchecks rows and columns for attack

    //while fabs(x[j]-i)==fabs(j-k) is to check diagonal attack

    if((x[j]==i)||((fabs(x[j]-i))==(fabs(j-k))))

    return 0;

    }return 1;

    }

    void queen::nQueens(int k)

    {//If i has reached n, we have a valid soln

    for(int i=1;i

  • 7/29/2019 Ada Lab Progs

    78/80

    }

    else

    nQueens(k+1); //recursively call nqueens()

    } //till i reaches n}}

    void queen::display() //function to display

    {int i,j;

    for( i=1;i

  • 7/29/2019 Ada Lab Progs

    79/80

    /*

    OUTPUT:******OUTPUT 1******

    enter the no. of queens6

    *Q****

    ***Q*******Q

    Q*****

    **Q***

    ****Q*******OUTPUT 2******

    enter the no. of queens

    4*Q**

    ***Q

    Q***

    **Q*

    */

  • 7/29/2019 Ada Lab Progs

    80/80