ada lab manual-rvce

77
MASTER OF COMPUTER APPLICATIONS IV SEMESTER 10MCA 48 Algorithms LAB Compiled by: Prof S.Anupamakumar Chandrashekhar B Dept of MCA,RVCE 1

Upload: julie-gallagher

Post on 14-Apr-2015

928 views

Category:

Documents


18 download

TRANSCRIPT

Page 1: Ada Lab Manual-rvce

MASTER OF COMPUTER APPLICATIONS

IV SEMESTER

10MCA 48Algorithms LAB

Compiled by: Prof S.Anupamakumar Chandrashekhar B

Dept of MCA,RVCE 1

Page 2: Ada Lab Manual-rvce

INDEX

Dept of MCA,RVCE 2

S.No Content Page No

1 List of Lab Programs 42 Do’s and Don’t’s in the Lab 63 Solutions to Lab Programs 84 Extra Questions 735 Viva Questions 746 Lab Cycles and Procedure for record writing 76

Page 3: Ada Lab Manual-rvce

LAB PROGRAMS

Dept of MCA,RVCE 3

Page 4: Ada Lab Manual-rvce

Dept of MCA,RVCE 4

Page 5: Ada Lab Manual-rvce

Dept of MCA,RVCE 5

Page 6: Ada Lab Manual-rvce

Do’s and Don’t in the LaboratoryDO …..

• Come prepared to the Lab.• Submit your Records to the Lecturer and sign in the Log Book on

entering the Lab.• Follow the Lab exercise cycles as instructed by the Department.

Violating the same will result in deduction of marks.• Use the same login assigned to you.• Put the chairs back to its position before you leave.• Backlog exercises should be executed after completing regular

exercises.

DON’T …..• Move around in the lab during the lab session.• Tamper System Files or Try to access the Server.• Write Data Sheets or Records in the Lab.• Change the system assigned to you without the notice of the Lab Staff.• Teaching your friends.

Dept of MCA,RVCE 6

Page 7: Ada Lab Manual-rvce

SOLUTIONS

Dept of MCA,RVCE 7

Page 8: Ada Lab Manual-rvce

INDEX

SL. No. CONTENT

Page No

1. Sort a given set of elements using the Quick sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator.

8

2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator.

18

3. a. Obtain the Topological ordering of vertices in a given digraph.b. Compute the transitive closure of a given directed graph using Warshall's algorithm

27

4. Implement 0/1 Knapsack problem using Dynamic Programming.

31

5. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm

34

6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.

38

7. a. Print all the nodes reachable from a given starting node in a digraph using BFS method. b. Check whether a given graph is connected or not using DFS method.

43

8. Find a subset of a given set S = sl,s2,.....,sn of n positive integers whose sum is equal to a given positive integer d. For example, if S= 1, 2, 5, 6, 8 and d = 9 there are two solutions1,2,6and1,8.A suitable message is to be displayed if the given problem instance doesn't have a solution.

51

Dept of MCA,RVCE 8

Page 9: Ada Lab Manual-rvce

9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation.

53

10.

Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.

59

11.

Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved.

63

12.

Implement N Queen's problem using Back Tracking. 69

Dept of MCA,RVCE 9

Page 10: Ada Lab Manual-rvce

1. Sort a given set of elements using Quick Sort method. Determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be searched and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator.

Quick Sort

Problem: To sort a set of elements and determine the time required to sor the

elements.

Method : It is used on the principle of divide-and-conquer method. Quick sort

works by partitioning a given array A[p . . r] into two non-empty sub array A[p . .

q] and A[q+1 . . r] such that every key in A[p . . q] is less than or equal to every

key in A[q+1 . . r]. Then the two sub arrays are sorted by recursive calls to Quick

sort. The exact position of the partition depends on the given array and index q is

computed as a part of the partitioning procedure.

Advantages:

• It requires otnly n log (n) time to sort n items. • It has an extremely short inner loop

Dis advantages

• It is recursive. Especially if recursion is not available, the implementation is extremely complicated.

• It requires quadratic (i.e., n2) time in the worst-case. • It is fragile i.e., a simple mistake in the implementation can go unnoticed and cause

it to perform badly.

Procedure for Quick sort

Quick Sort

If p < r then

q Partition (A, p, r)

Dept of MCA,RVCE 10

Page 11: Ada Lab Manual-rvce

Recursive call to Quick Sort (A, p, q)

Recursive call to Quick Sort (A, q + r, r)

Source Code

#include<stdio.h>

#include<sys/time.h>

#include<stdlib.h>

#define MAX 1000

struct Timer

int limit;

int time;

mytimer[10];

void quicksort(int a[],int low,int high)

int j;

if(low<high)

j=partition(a,low,high);

quicksort(a,low,j-1);

quicksort(a,j+1,high);

int partition(int a[],int low,int high)

int i,j,temp,key;

key=a[low];

i=low+1;

j=high;

while(1)

Dept of MCA,RVCE 11

Page 12: Ada Lab Manual-rvce

while(i<high && key>=a[i])

i++;

while(key<a[j])

j--;

if(i<j)

temp=a[i];

a[i]=a[j];

a[j]=temp;

else

temp=a[low];

a[low]=a[j];

a[j]=temp;

return j;

int main(int argc, char ** argv)

int i,n,a[MAX],k;

struct timeval st,en;

printf("----------------------------\n Loop will Run MAX 10 Times (To break press

zero(0)\n----------------------\n");

for(k=0;k<10;k++)

printf("\nEnter the number of elements\n");

scanf("%d",&n);

if(n<=0) break;

Dept of MCA,RVCE 12

Page 13: Ada Lab Manual-rvce

switch(argc)

case 2:for(i=0;i<n;i++)

a[i]=rand()% 1000;

printf(" %5d ",a[i]);

break;

default:printf("\n Enter %d Elements \n ",n);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

gettimeofday(&st,0);

quicksort(a,0,n-1);

gettimeofday(&en,0);

printf("\n The Sorted array is \n");

for(i=0;i<n;i++)

printf("%d\t",a[i]);

printf("\nTime taken= %d Micro

Seconds",mytimer[k].time=(en.tv_usec-st.tv_usec));

mytimer[k].limit=n;

printf("\n Data Limit Time taken\n");

for(k--;k>=0;k--)

printf("%5d %5d \n",mytimer[k].limit,mytimer[k].time);

return 0;

Enter the number of elements

10

Dept of MCA,RVCE 13

Page 14: Ada Lab Manual-rvce

383 886 777 915 793 335 386 492 649 421

The Sorted array is

335 383 386 421 492 649 777 793 886 915

Time taken= 3 Micro Seconds

Enter the number of elements

100

362 27 690 59 763 926 540 426 172 736 211 368 567 429 782 530 862 123 67 135 929 802 22 58 69 167 393 456 11 42 229 373 421 919 784 537 198 324 315 370 413 526 91 980 956 873 862 170 996 281 305 925 84 327 336 505 846 729 313 857 124 895 582 545 814 367 434 364 43 750 87 808 276 178 788 584 403 651 754 399 932 60 676 368 739 12 226 586 94 539 795 570 434 378 467 601 97 902 317 492

The Sorted array is

11 12 22 27 42 43 58 59 60 67 69 8487 91 94 97 123 124 135 167 170 172 178198 211 226 229 276 281 305 313 315 317 324327 336 362 364 367 368 368 370 373 378 393399 403 413 421 426 429 434 434 456 467 492505 526 530 537 539 540 545 567 570 582 584586 601 651 676 690 729 736 739 750 754 763782 784 788 795 802 808 814 846 857 862 862873 895 902 919 925 926 929 932 956 980 996

Time taken= 15 Micro Seconds

Enter the number of elements

1000

652 756 301 280 286 441 865 689 444 619 440 729 31 117 97 771 481 675 709 927 567 856 497 353 586 965 306 683 219 624 528 871 732 829 503 19 270 368 708 715 340 149 796 723 618 245 846 451 921 555 379 488 764 228 841 350 193 500 34 764 124 914 987 856 743 491 227 365 859 936 432 551 437 228 275 407 474 121 858 395 29 237 235 793 818 428 143 11 928 529 776 404 443 763 613 538 606 840 904 818 128 688 369 917 917 996 324 743 470 183 490 499 772 725 644 590 505 139 954 786 669 82 542 464 197 507 355 804 348 611 622 828 299 343 746 568 340 422 311 810 605 801 661 730 878 305 320 736 444 626 522 465 708 416 282 258 924 637 62 624 600 36 452 899 379 550 468 71 973 131 881 930 933 894 660 163 199 981 899 996 959 773 813 668 190 95 926 466 84 340 90 684 376 542 936

Dept of MCA,RVCE 14

Page 15: Ada Lab Manual-rvce

107 445 756 179 418 887 412 348 172 659 9 336 210 342 587 206 301 713 372 321 255 819 599 721 904 939 811 940 667 705 228 127 150 984 658 920 224 422 269 396 81 630 84 292 972 672 850 625 385 222 299 640 42 898 713 298 190 524 590 209 581 819 336 732 155 994 4 379 769 273 776 850 255 860 142 579 884 993 205 621 567 504 613 961 754 326 259 944 202 202 506 784 21 842 868 528 189 872 908 958 498 36 808 753 248 303 333 133 648 890 754 567 746 368 529 500 46 788 797 249 990 303 33 363 497 253 892 686 125 152 996 975 188 157 729 436 460 414 921 460 304 28 27 50 748 556 902 794 697 699 43 39 2 428 403 500 681 647 538 159 151 535 134 339 692 215 127 504 629 49 964 285 429 343 335 177 900 238 971 949 289 367 988 292 795 743 144 829 390 682 340 541 569 826 232 261 42 360 117 23 761 81 309 190 425 996 367 677 234 690 626 524 57 614 168 205 358 312 386 100 346 726 994 916 552 578 529 946 290 647 970 51 80 631 593 857 627 312 886 214 355 512 90 412 479 610 969 189 274 355 641 620 433 987 888 338 566 770 284 856 417 606 260 849 237 205 59 217 518 945 783 873 458 873 637 289 483 607 478 757 314 471 729 100 459 618 438 25 388 74 233 157 681 493 358 270 699 417 839 569 363 622 794 173 847 431 462 682 390 292 791 57 115 521 157 574 491 947 951 231 21 537 740 54 30 98 325 81 516 516 2 231 139 796 404 338 580 218 21 970 862 812 379 977 685 536 904 176 483 207 759 857 744 499 911 127 950 236 560 818 105 563 49 244 711 805 934 291 375 955 614 589 768 993 918 805 882 822 982 717 30 93 574 126 593 486 253 543 74 814 713 179 377 762 775 88 919 710 732 294 17 346 235 137 691 153 943 573 328 925 291 710 18 217 836 963 55 90 858 130 904 571 661 633 685 789 73 604 851 805 250 868 503 485 6 195 639 949 120 967 226 763 677 596 981 865 560 36 955 770 518 211 342 532 196 379 321 270 984 172 427 234 40 283 72 398 830 63 347 950 30 573 714 59 522 47 924 82 435 232 204 954 443 898 486 640 278 159 262 262 683 41 848 723 324 272 122 154 335 821 457 365 747 171 776 269 218 701 703 653 933 907 959 728 806 797 720 84 308 334 698 991 376 898 715 52 171 189 559 506 10 16 224 109 539 0 378 109 53 81 114 338 989 426 67 147 223 787 231 532 122 281 875 850 179 590 254 350 131 813 857 494 181 81 603 720 433 982 181 487 415 296 825 404 722 892 551 297 32 134 181 506 415 57 708 595 999 962 297 483 776 154 977 309 587 932 382 21 266 563 860 682 211 685 86 285 930 990 583 314 476 116 820 892 525 528 839 525 490 136 360 618 643 337 928 582 621 310 955 888 225 815 570 437 853 8 722 783 350 657 97 827 126 269 71 651 149 910 528 639 398 888 610 393 577 890 976 199 552 931 87 777 99 657 566 952 17 641 735 368 298 184 195 776 805

Dept of MCA,RVCE 15

Page 16: Ada Lab Manual-rvce

266 428 954 528 308 593 278 197 555 672 774 445 0 325 997 283 412 127 382 421 693 334 439 334 421 159 985 957 354 761 762 972 541 716 852 850 662 482 399 217 154 173 15 506 851 364 790 263 491 172 37 537 859 828 871 280 987 856 590 341 970 352 665 511 69 517 361 83 351 112 300 506 638 667 364 489 32 154 104 875 679 141 412 538 969 636 170 956 844 760 649 814 465 314 326 886 183 39 969 535 152 621 393 790 289 109 631 673 264 735 548 295 877 313 833 198 949 355 155 793 468 156 960 933 823 286 171 358 677 140

The Sorted array is

0 2 2 4 6 8 9 10 11 15 1617 17 18 19 21 21 21 21 23 25 2728 29 30 30 30 31 32 32 33 34 3636 36 37 39 39 40 41 42 42 43 4647 49 49 50 51 52 53 54 55 57 5757 59 59 62 63 67 69 71 71 72 7374 74 80 81 81 81 81 81 82 82 8384 84 84 86 87 88 90 90 90 93 9597 97 98 99 100 100 104 105 107 109 109109 112 114 115 116 117 117 120 121 122 122124 125 126 126 127 127 127 127 128 130 131131 133 134 134 136 137 139 139 140 141 142143 144 147 149 149 150 151 152 152 153 154154 154 154 155 155 156 157 157 157 159 159159 163 168 170 171 171 171 172 172 172 173173 176 177 179 179 179 181 181 181 183 183184 188 189 189 189 190 190 190 193 195 195196 197 197 198 199 199 202 202 204 205 205205 206 207 209 210 211 211 214 215 217 217217 218 218 219 222 223 224 224 225 226 227228 228 228 231 231 231 232 232 233 234 234235 235 236 237 237 238 244 245 248 249 250253 253 254 255 255 258 259 260 261 262 262263 264 266 266 269 269 269 270 270 270 272273 274 275 278 278 280 280 281 282 283 283284 285 285 286 286 289 289 289 290 291 291292 292 292 294 295 296 297 297 298 298 299299 300 301 301 303 303 304 305 306 308 308309 309 310 311 312 312 313 314 314 314 320321 321 324 324 325 325 326 326 328 333 334334 334 335 335 336 336 337 338 338 338 339340 340 340 340 341 342 342 343 343 346 346347 348 348 350 350 350 351 352 353 354 355355 355 355 358 358 358 360 360 361 363 363

Dept of MCA,RVCE 16

Page 17: Ada Lab Manual-rvce

364 364 365 365 367 367 368 368 368 369 372375 376 376 377 378 379 379 379 379 379 382382 385 386 388 390 390 393 393 395 396 398398 399 403 404 404 404 407 412 412 412 412414 415 415 416 417 417 418 421 421 422 422425 426 427 428 428 428 429 431 432 433 433435 436 437 437 438 439 440 441 443 443 444444 445 445 451 452 457 458 459 460 460 462464 465 465 466 468 468 470 471 474 476 478479 481 482 483 483 483 485 486 486 487 488489 490 490 491 491 491 493 494 497 497 498499 499 500 500 500 503 503 504 504 505 506506 506 506 506 507 511 512 516 516 517 518518 521 522 522 524 524 525 525 528 528 528528 528 529 529 529 532 532 535 535 536 537537 538 538 538 539 541 541 542 542 543 548550 551 551 552 552 555 555 556 559 560 560563 563 566 566 567 567 567 568 569 569 570571 573 573 574 574 577 578 579 580 581 582583 586 587 587 589 590 590 590 590 593 593593 595 596 599 600 603 604 605 606 606 607610 610 611 613 613 614 614 618 618 618 619620 621 621 621 622 622 624 624 625 626 626627 629 630 631 631 633 636 637 637 638 639639 640 640 641 641 643 644 647 647 648 649651 652 653 657 657 658 659 660 661 661 662665 667 667 668 669 672 672 673 675 677 677677 679 681 681 682 682 682 683 683 684 685685 685 686 688 689 690 691 692 693 697 698699 699 701 703 705 708 708 708 709 710 710711 713 713 713 714 715 715 716 717 720 720721 722 722 723 723 725 726 728 729 729 729730 732 732 732 735 735 736 740 743 743 743744 746 746 747 748 753 754 754 756 756 757759 760 761 761 762 762 763 763 764 764 768769 770 770 771 772 773 774 775 776 776 776776 776 777 783 783 784 786 787 788 789 790790 791 793 793 794 794 795 796 796 797 797801 804 805 805 805 805 806 808 810 811 812813 813 814 814 815 818 818 818 819 819 820821 822 823 825 826 827 828 828 829 829 830833 836 839 839 840 841 842 844 846 847 848849 850 850 850 850 851 851 852 853 856 856856 856 857 857 857 858 858 859 859 860 860862 865 865 868 868 871 871 872 873 873 875

Dept of MCA,RVCE 17

Page 18: Ada Lab Manual-rvce

875 877 878 881 882 884 886 886 887 888 888888 890 890 892 892 892 894 898 898 898 899899 900 902 904 904 904 904 907 908 910 911914 916 917 917 918 919 920 921 921 924 924925 926 927 928 928 930 930 931 932 933 933933 934 936 936 939 940 943 944 945 946 947949 949 949 950 950 951 952 954 954 954 955955 955 956 957 958 959 959 960 961 962 963964 965 967 969 969 969 970 970 970 971 972972 973 975 976 977 977 981 981 982 982 984984 985 987 987 987 988 989 990 990 991 993993 994 994 996 996 996 996 997 999

Time taken= 182 Micro Seconds

Enter the number of elements0

Data Limit Time taken

1000 182

100 15

10 3

2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator.

Problem : To sort a given set of records using merge sort. The program should use openMP to parallelize the mergesort.Method :

Merge Sort

3. Merge-sort is based on the divide-and-conquer paradigm. The Merge-sort algorithm

can be described in general terms as consisting of the following three steps:

4. 1. Divide Step

5. If given array A has zero or one element, return S; it is already sorted. Otherwise,

divide A into two arrays, A1 and A2, each containing about half of the elements of A.

6. 2. Recursion Step

Dept of MCA,RVCE 18

Page 19: Ada Lab Manual-rvce

7. Recursively sort array A1 and A2.

8. 3. Conquer Step

9. Combine the elements back in A by merging the sorted arrays A1 and A2 into a

sorted sequence.

10. Merge sort has a guaranteed n log n running time. Meaning merge sort

works

11.n log n in worst, best and average cases.

To begin, suppose that we have two sorted arrays A1[1], A1[2], . . , A1[M] and A2[1],

A2[2], . . . , A2[N]. The following is a direct algorithm of the obvious strategy of

successively choosing the smallest remaining elements from A1 to A2 and putting it in A.

Open MP

OpenMP is an Application Program Interface (API), jointly defined by a group of major

computer hardware and software vendors. OpenMP provides a portable, scalable model for

developers of shared memory parallel applications. The API supports C/C++ and Fortran

on a wide variety of architectures.

Open MP Model:

1. Shared Memory, Thread Based Parallelism:

OpenMP is based upon the existence of multiple threads in the shared memory programming paradigm. A shared memory process consists of multiple threads.

2. Explicit Parallelism:

OpenMP is an explicit (not automatic) programming model, offering the programmer full control over parallelization.

3. Fork - Join Model:

OpenMP uses the fork-join model of parallel execution:

List of Open MPFunctions Used in Mergesort:

1. #include<omp.h> : It is the header file which should be used to implement the functions using open MP

2.#pragma omp parallel private(var1, var2) shared(var3)

Parallel section executed by all threads

Dept of MCA,RVCE 19

Page 20: Ada Lab Manual-rvce

. . .

All threads join master thread and disband

This section is used to parallelize all the sections using threds.

3. #pragma omp sections nowait : Helps to define the progam using different sections so that it can be run parallely.

Execution : To execute programs using open MP concepts the command is

gcc -fopenmp filename.c

Procedure:

MERGE (A1, A2, A)

i.← j 1A1[m+1], A2[n+1] ← INT_MAXFor k ←1 to m + n do if A1[i] < A2[j] then A[k] ← A1[i] i ← i +1 else A[k] ← A2[j] j ← j + 1

Merge Sort Algorithm

MERGE_SORT (A)

A1[1 . . n/2 ] ← A[1 . . n/2 ]

A2[1 . . n/2 ] ← A[1 + n/2 . . n] Merge Sort (A1)Merge Sort (A1)Merge Sort (A1, A2, A)

Source Code

#include<stdio.h>

Dept of MCA,RVCE 20

Page 21: Ada Lab Manual-rvce

#include<sys/time.h>

#include<omp.h>

#include<stdlib.h>

#define MAX 1000

struct Timer

int limit;

int time;

mytimer[10];

void mergesort(int ar[], int,int);

void merge(int [], int,int,int);

int main(int argc,int argv)

int a[MAX],i,n,k,g;

struct timeval st,en;

printf(" Loop will run MAX 10 times ( to break press zero\n");

for(k=0;k<10;k++)

printf("\n enter the number of elements\n");

scanf("%d",&n);

if(n<=0) break;

switch(argc)

Dept of MCA,RVCE 21

Page 22: Ada Lab Manual-rvce

case 2: for(i=0;i<n;i++)

a[i]=rand()% MAX;

printf("%5d",a[i]);

break;

default : printf("Enter %d Elements\n",n);

for(i=0;i<n;i++)

scanf("%d",&a[i]);

gettimeofday(&st,0);

mergesort(a,0,n-1);

gettimeofday(&en,0);

printf("\n The sorted array is \n");

for(i=0;i<n;i++)

printf("%d\t",a[i]);

printf("\nTime taken = %d Micro seconds ",mytimer[k].time=(en.tv_usec-st.tv_usec));

mytimer[k].limit=n;

printf("\n Data Limit Time Taken \n");

for(k--;k>=0;k--)

Dept of MCA,RVCE 22

Page 23: Ada Lab Manual-rvce

printf("%5d %5d \n",mytimer[k].limit,mytimer[k].time);

return 0;

void mergesort(int a[], int low, int high)

int mid;

if(low < high)

mid = (low+high)/2;

mergesort(a,low,mid);

mergesort(a,mid+1,high);

merge(a,low,mid,high);

void merge(int a[], int low, int mid, int high)

int i,j,h,k,b[MAX];

int nthreads,tid;

#pragma omp parallel shared(a,low,mid,high,nthreads) private(i,tid)

tid=omp_get_thread_num();if (tid==0)

Dept of MCA,RVCE 23

Page 24: Ada Lab Manual-rvce

nthreads=omp_get_num_threads();

printf("number of threads %d\n",nthreads);

printf("thread %d starting \n",tid);

#pragma omp sections nowait

printf("thread %d doing section 1 \n",tid);

h=i=low;

j=mid+1;

//for (h=low,j=mid+1;h<=mid,j<=high;h++,j++)

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

if(a[h] < a[j])

b[i++] = a[h++];

else

b[i++] = a[j++];

#pragma omp section

Dept of MCA,RVCE 24

Page 25: Ada Lab Manual-rvce

if(h>mid)

for(k=j;k<=high;k++)

b[i++] = a[k];

else

for(k=h;k<=mid;k++)

b[i++]=a[k];

#pragma omp section

for(k=low;k<=high;k++)

a[k]=b[k];

printf ("thread in section 2 %d\n",tid);

Output: ./a.out 1

Loop will run MAX 10 times ( to break press zero

enter the number of elements

10

383 886 777 915 793 335 386 492 649 421number of threads 4

thread 0 starting

Dept of MCA,RVCE 25

Page 26: Ada Lab Manual-rvce

thread 0 doing section 1

thread in section 2 0

thread 1 starting

thread 2 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

Dept of MCA,RVCE 26

Page 27: Ada Lab Manual-rvce

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 3 starting

thread 1 starting

number of threads 4

thread 0 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 1 starting

number of threads 4

Dept of MCA,RVCE 27

Page 28: Ada Lab Manual-rvce

thread 0 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

The sorted array is

335 383 386 421 492 649 777 793 886 915

Time taken = 1334 Micro seconds enter the number of elements

5

362 27 690 59 763number of threads 4

Dept of MCA,RVCE 28

Page 29: Ada Lab Manual-rvce

thread 0 starting

thread 0 doing section 1

thread in section 2 0

thread 1 starting

thread 2 starting

thread 3 starting

thread 1 starting

thread 1 doing section 1

thread in section 2 1

thread 3 starting

thread 2 starting

number of threads 4

thread 0 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

thread 2 starting

thread 2 doing section 1

thread in section 2 2

Dept of MCA,RVCE 29

Page 30: Ada Lab Manual-rvce

thread 1 starting

number of threads 4

thread 0 starting

thread 3 starting

The sorted array is

27 59 362 690 763

Time taken = 59360 Micro seconds

enter the number of elements

0

Data Limit Time Taken

5 59360

10 1334

3a.Obtain the Topological ordering of vertices in a given digraph.

Problem: To order/sort the given vertices of a given digraph

Method:

A cycle in a diagraph or directed graph G is a set of edges, (v1, v2), (v2, v3), ..., (vr −1, vr) where v1 = vr. A diagraph is acyclic if it has no cycles. Such a graph is often referred to as a directed acyclic graph, or DAG, for short. This uses the basic traversal techniques to order the vertices

Procedure:The topological ordering is done using :

for(i=0;i<n;i++)for(j=0;j<n;j++)indeg[i]=indeg[i]+a[j][i];

while(count<n)

Dept of MCA,RVCE 30

Page 31: Ada Lab Manual-rvce

for(k=0;k<n;k++)

if((indeg[k]==0) && (flag[k]==0))printf("%d,,(k+1)); flag [k]=1;

for(i=0;i<n;i++)

if(a[i][k]==1)indeg[k]--;

count++;

Source Code:

#include <stdio.h>#include <stdlib.h># include <math.h>

int main()

int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;printf("Enter the no of vertices:");scanf("%d",&n);printf("Enter the adjacency matrix:");for(i=0;i<n;i++)

for(j=0;j<n;j++)scanf("%d",&a[i][j]);

for(i=0;i<n;i++)

indeg[i]=0;flag[i]=0;

for(i=0;i<n;i++)

for(j=0;j<n;j++)indeg[i]=indeg[i]+a[j][i];

printf("The topological order is:");while(count<n)

Dept of MCA,RVCE 31

Page 32: Ada Lab Manual-rvce

for(k=0;k<n;k++)

if((indeg[k]==0) && (flag[k]==0))

printf("%d",(k+1)); flag [k]=1;

for(i=0;i<n;i++)

if(a[i][k]==1)indeg[k]--;

count++;

return 0;

Enter the no of vertices:4

Enter the adjacency matrix:

0 1 1 00 0 1 00 0 1 00 0 0 0The topological order is : 1234

3 b. Compute the transitive closure of a given directed graph using Warshall’s algorithm.

Warshall’s algorithm is used to find the transitive closure of a directed graph. This is the application of dynamic programming technique.

Transitive Closure Transitive closure of an directed graph with n vertices can be defined as the n-by-n Boolean matrix T=tij in which the element in the ith row (1≤i≤n) and the jth column (1≤j≤n) is 1 if there exists a nontrivial directed path( a directed path of a positive length) from ith vertex to the jth vertex otherwise tij is 0.

Dept of MCA,RVCE 32

Page 33: Ada Lab Manual-rvce

Warshall's Algorithm Warshall (int N, bmatrix &A, bmatrix &P) int i,j,k; for (i = 0; i < N; i++) for (j = 0; j < N; j++) /* There's a path if there's an edge */ P[i][j] = A[i][j]; for (k = 0; k < N; k++) for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (! P[i][j]) P[i][j] = P[i][k] && P[k][j]; /* Warshall */

Source Code:

#include<stdio.h>#define MAX 10void warshall(int p[10][10],int n);void main()int p[10][10],i,j,n;printf("\n Enter the number of vertices\n :");scanf("%d",&n);

printf("Enter adj mattrix ..\n");for(i=1;i<=n;i++)for (j=1;j<=n;j++)scanf("%d",&p[i][j]);

warshall(p,n); for(i=1;i<=n;i++)

for (j=1;j<=n;j++) printf("\t%d",p[i][j]); printf("\n");void warshall(int p[10][10],int n)int i,j,k;

Dept of MCA,RVCE 33

Page 34: Ada Lab Manual-rvce

for(k=1;k<=n;k++)for(i=1;i<=n;i++)if(p[i][k]==1)for (j=1;j<=n;j++) p[i][j]=p[i][j] || p[k][j];

Enter the number of vertices :4

Enter adj mattrix ..

0 1 0 00 0 0 10 0 0 01 0 1 0

Transitive closure(Path Matrix) is 1 1 1 1

1 1 1 1 0 0 0 0

1 1 1 1

4. Implement 0/1 Knapsack problem using dynamic programming.

knapsack problem

We have a knapsack that has capacity (weight) C and have several items I1,…,In.Each item Ij has a weight wj and a benefit bj.we want to place a certain number of copies of each item Ij in the knapsack so that:(i)The knapsack weight capacity is not exceeded and(ii)The total benefit is maximal.

Method:

A greedy optimal solution can be used to solve the knapsack problem.

Procedure:

int knapsack(int i,int m)

if(i==n)

return(m<w[n])?0:p[n];

if(m<w[i])

Dept of MCA,RVCE 34

Page 35: Ada Lab Manual-rvce

return knapsack(i+1,m);

return maxi(knapsack(i+1,m),knapsack(i+1,m-w[i])+p[i]);

Source Code:

#include<stdio.h>

#define max 30

#define true 1

#define false 0

int knapsack(int,int);

int maxi(int,int);

int p[max];

int w[max];

int n;

int main()

int m,cu,optsoln, i;

printf("Enter the no. of Objects:\n");

scanf("%d",&n);

printf("Enter the weights:\n");

for(i=1;i<=n;i++)

scanf("%d",&w[i]);

printf("Enter the profits:\n");

for(i=1;i<=n;i++)

Dept of MCA,RVCE 35

Page 36: Ada Lab Manual-rvce

scanf("%d",&p[i]);

printf("Enter the knapsack capacity:");

scanf("%d",&m);

printf("\nWeights Profits");

for(i=1;i<=n;i++)

printf("\n%5d %13d",w[i],p[i]);

printf("\nKnapsack capacity %3d",m);

optsoln=knapsack(1,m);

printf("\n\nOptimal solution = %d\n",optsoln);

int knapsack(int i,int m)

if(i==n)

return(m<w[n])?0:p[n];

if(m<w[i])

return knapsack(i+1,m);

return maxi(knapsack(i+1,m),knapsack(i+1,m-w[i])+p[i]);

int maxi(int a,int b)

if(a>b)

return a;

else return b;

Dept of MCA,RVCE 36

Page 37: Ada Lab Manual-rvce

Enter the no. of Objects:4Enter the weights:2 1 3 2Enter the profits:12 10 20 15Enter the knapsack capacity:5Weights Profits

2 12

1 10

3 20

2 15Knapsack capacity 5Optimal solution = 37

5. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra’s algorithm.

Problem

Considering a directed graph G = (V, E). Determine the length of the shortest path

from the source to each of the other nodes of the graph. This problem can be solved by a

greedy algorithm often called Dijkstra's algorithm.

Method:

The algorithm maintains two sets of vertices, S and C. At every stage the set S contains

those vertices that have already been selected and set C contains all the other vertices.

Hence we have the invariant property V=S U C. When algorithm starts Delta contains only

the source vertex and when the algorithm halts, Delta contains all the vertices of the graph

and problem is solved. At each step algorithm choose the vertex in C whose distance to the

source is least and add it to S.

Procedure:

Void shortestpath(int v,int cost[][MAX],int dist[],int n)

Dept of MCA,RVCE 37

Page 38: Ada Lab Manual-rvce

int s[MAX];

int u,i,j,w,num;

for(i=1;i<=n;i++)

s[i]=FALSE;

dist[i]=cost[v][i];

s[v]=TRUE;

dist[v]=1;

num=2;

while(num<=n)

u=choose(dist,s,n);

s[u]=TRUE;

num++;

for(w=1;w<=n;w++)

if(((dist[u]+cost[u][w])<dist[w]) && !s[w])

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

Source Code

#include<stdio.h>

#define MAX 10

#define TRUE 1

#define FALSE 0

#define INFINITY 9999

void shortestpath(int,int [][MAX],int [],int);

int choose(int [],int [],int);

Dept of MCA,RVCE 38

Page 39: Ada Lab Manual-rvce

void main()

int cost[MAX][MAX];

int dist[MAX];

int i,j,n;

int v;

printf("Enter the no. of vertices:");

scanf("%d",&n);

printf("Enter the cost matrix(row wise)\n");

printf("-Enter 9999 for noedge or INFINITY \n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

scanf("%d",&cost[i][j]);

printf("Enter the starting node:");

scanf("%d",&v);

shortestpath(v,cost,dist,n);

printf("Shortest path from starting node to Destination Node is as shown below\n");

printf("Destination Node | Distance\n");

for(j=1;j<=n;j++)

if(j!=v)

printf("%15d | %5d\n",j,dist[j]);

void shortestpath(int v,int cost[][MAX],int dist[],int n)

int s[MAX];

int u,i,j,w,num;

for(i=1;i<=n;i++)

Dept of MCA,RVCE 39

Page 40: Ada Lab Manual-rvce

s[i]=FALSE;

dist[i]=cost[v][i];

s[v]=TRUE;

dist[v]=1;

num=2;

while(num<=n)

u=choose(dist,s,n);

s[u]=TRUE;

num++;

for(w=1;w<=n;w++)

if(((dist[u]+cost[u][w])<dist[w]) && !s[w])

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

int choose(int dist[],int s[],int n)

int w,j=1,min;

min=INFINITY;

for(w=1;w<=n;w++)

if((dist[w]<min) && (s[w]==FALSE))

min=dist[w];

j=w;

Dept of MCA,RVCE 40

Page 41: Ada Lab Manual-rvce

return(j);

Enter the no. of vertices:6Enter the cost matrix(row wise)-Enter 9999 for noedge or INFINITY

0 15 10 9999 45 99999999 0 15 9999 20 999920 9999 0 0 9999 9999 9999 10 9999 0 35 9999 9999 9999 9999 30 0 9999 9999 9999 9999 4 9999 0Enter the starting node:5

Shortest path from starting node to Destination Node is as shown below

Destination Node | Distance

1 | 75

2 | 40

3 | 55

4 | 30

6 | 9999

6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s

algorithm.

Problem:

To find the minimum cost spanning tree of a given undirected graph using kruskals

method

Mehtod:

A spanning tree of a graph is any tree that includes every vertex in the graph. Little more

formally, a spanning tree of a graph G is a sub-graph of G that is a tree and contains all the

Dept of MCA,RVCE 41

Page 42: Ada Lab Manual-rvce

vertices of G. An edge of a spanning tree is called a branch; an edge in the graph that is not

in the spanning tree is called a chord. We construct spanning tree whenever we want to

find a simple, cheap and yet efficient way to connect a set of terminals (computers, cites,

factories, etc.). Spanning trees are important because of following reasons.

• Spanning trees construct a sparse sub graph that tells a lot about the original graph. • Spanning trees a very important in designing efficient routing algorithms. • Some hard problems (e.g., Steiner tree problem and traveling salesman problem)

can be solved approximately by using spanning trees. • Spanning trees have wide applications in many areas, such as network design, etc.

Procedure

Minimum Spanning Tree (MST)

A minimum spanning tree of a weighted graph G is a spanning tree of G whose edges sum

is minimum weight. In other words, a MST is a tree formed from a subset of the edges in a

given undirected graph, with two properties:

It spans the graph, i.e., it includes every vertex of the graph.

It is a minimum, i.e., the total weight of all the edges is as low as possible.

Source Code

#include<stdio.h>

typedef struct

int node1;

int node2;

int wt;

edge;

void sortedges(edge a[],int n)

int i,j;

edge temp;

for(i=0;i< n-1;++i)

for(j=i+1;j< n;++j)

Dept of MCA,RVCE 42

Page 43: Ada Lab Manual-rvce

if(a[i].wt>a[j].wt)

temp=a[i];

a[i]=a[j];

a[j]=temp;

int checkcycle(int p[],int i,int j)

int v1,v2;

v1 = i;

v2 = j;

while(p[i]>-1)

i = p[i];

while(p[j]>-1)

j = p[j];

if(i!=j)

p[j]=i;

printf("%d %d\n",v1,v2);

return 1;

return 0;

int main()

edge e[100];

int parent[100];

int n,i,j,m,k = 1,cost = 0;

printf("KRUSKAL's ALGORITHM\n");

printf("Enter number of nodes\n");

scanf("%d",&n);

for(i=0;i< n;++i)

Dept of MCA,RVCE 43

Page 44: Ada Lab Manual-rvce

parent[i]=-1;

printf("Enter number of edges\n");

scanf("%d",&m);

for(i=0;i< m;++i)

printf("enter an edge and wt\n");

scanf("%d %d %d", &e[i].node1,&e[i].node2,&e[i].wt);

sortedges(e,m);

printf("\n\nEdges of the tree\n");

i = 0;

while(k< n)

if(checkcycle(parent,e[i].node1,e[i].node2))

k++;

cost=cost+e[i].wt;

i++;

printf("cost = %d",cost);

return 0;

Enter the number of nodes

10

Enter the number of edges

10

Enter the edge list

Enter the next edge(u,v)

1

2

Enter the cost

Dept of MCA,RVCE 44

Page 45: Ada Lab Manual-rvce

8

Enter the next edge(u,v)

9

9

Enter the cost

0

Enter the next edge(u,v)

7

7

Enter the cost

77

Enter the next edge(u,v)

8

9

Enter the cost

78

Enter the next edge(u,v)

8

9

Enter the cost

8

Enter the next edge(u,v)

9

9

Enter the cost

8

Enter the next edge(u,v)

8

9

Enter the cost

Dept of MCA,RVCE 45

Page 46: Ada Lab Manual-rvce

8

Enter the next edge(u,v)

89

88

Enter the cost

88

Enter the next edge(u,v)

8

89

Enter the cost

0

Enter the next edge(u,v)

89

88

Enter the cost

9

Output

spanning tree donot exist

7a. Print all the nodes reachable from a given starting node in a digraph using BFS

method.

Problem:

To find all the reachable nodes using Breadth First Search

Method:

The algorithm uses traversal techniques to reach the nodes

Procedure:

Algorithm BFS(G)

// Implements a BFS traversal of a given graph

// Input: Graph = (V,E)

Dept of MCA,RVCE 46

Page 47: Ada Lab Manual-rvce

// output: Graph G with its vertices marked with consecutive integers in the order

they have been visited by the BFS traversal mark each vertex in V with 0 as a mark

of being “unvisited”

Count <- 0

For each vertex v in V do

If v is marked with 0

bfs(v)

bfs(v)

// Visits all the unvisited vertices connected to vertex v and assigns them the

numbers in the order they are visited via global variable count

count = count + 1

// mark v with count and initialize a queue with v

while the queue is not empty do

for each vertex w in v adjacent to the fronts vertex v do

if w is marked with 0

count = count + 1

add w to the queue

remove vertex v from the front of the queue

First, each vertex is clearly marked at most once, added to the list at most once

(since that happens only when it's marked), and therefore removed from the list at most

once. Since the time to process a vertex is proportional to the length of its adjacency list,

the total time for the whole algorithm is O(m).

Usage: Use of breadth first search arises in certain pattern matching problems.

Source Code

#include<stdio.h>

#define MAX 20

int cnt=1;

void main()

Dept of MCA,RVCE 47

Page 48: Ada Lab Manual-rvce

int i,j,a[MAX][MAX],cov[MAX],q[MAX];

int n,strt;

printf("Enter the total Number of Nodes:");

scanf("%d",&n);

printf("Enter Matrix\n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

scanf("%d",&a[i][j]);

printf("Entered Matrix\n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

printf("%3d",a[i][j]);

printf("\n");

printf("Enter the start vertex\n");

scanf("%d",&strt);

for(i=1;i<=MAX;i++)

q[i]=0;

cov[i]=0;

cov[strt]=1;

q[1]=strt;

j=1;

while(q[j]!=0)

cov[q[j]]=1;

for(i=1;i<=n;i++)

if((a[q[j]][i]==1) && !cov[i])

Dept of MCA,RVCE 48

Page 49: Ada Lab Manual-rvce

q[++cnt]=i;

cov[i]=1;

j++;

for(i=1;i<=cnt;i++)

printf(" %3d->",q[i]);

printf("\t\t %d",q[i]);

Enter the total Number of Nodes:10

Enter Matrix 0 1 1 0 0 0 0 0 0 0

0 0 0 0 1 0 0 0 0 0

0 0 0 0 0 1 0 0 0 0

0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 0 1 0 0

0 0 0 0 0 0 0 1 0 0

0 0 0 0 0 0 0 1 1 0

0 0 0 0 0 0 0 0 0 1

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 1 0

Entered Matrix is 0 1 1 0 0 0 0 0 0 0

0 0 0 0 1 0 0 0 0 0

0 0 0 0 0 1 0 0 0 0

Dept of MCA,RVCE 49

Page 50: Ada Lab Manual-rvce

0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 0 1 0 0

0 0 0 0 0 0 0 1 0 0

0 0 0 0 0 0 0 1 1 0

0 0 0 0 0 0 0 0 0 1

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 1 0Enter the start vertex1

4 47 79 98 8

vertex 0is not reachable

vertex1is reachable

vertex 2is not reachable

vertex 3is not reachable

vertex4is reachable

vertex 5is not reachable

vertex 6is not reachable

vertex7is reachable

vertex8is reachable

vertex9is reachable

Dept of MCA,RVCE 50

Page 51: Ada Lab Manual-rvce

7.b Check whether a given graph is connected or not using DFS method

Problem : To check the connectivity of the graph using DFS method.

Method:

Depth first search is another way of traversing graphs, which is closely related to preorder

traversal of a tree. Recall that preorder traversal simply visits each node before its children.

It is most easy to program as a recursive routine:

preorder(node v)

visit(v);

for each child w of v

preorder(w);

To turn this into a graph traversal algorithm, we basically replace "child" by "neighbor".

But to prevent infinite loops, we only want to visit each vertex once. We can use marks to

keep track of the vertices that have already been visited, and not visit them again. Also, we

can use this search to build a spanning tree with certain useful properties.

Procedure:

dfs (vertex v)

visit(v);

for each neighbor w of v

if w is unvisited

dfs(w);

add edge vw to tree T

Source Code:

#include <stdio.h>

Dept of MCA,RVCE 51

Page 52: Ada Lab Manual-rvce

int a[10][10];

void main()

int j,i;

int n,s,cov[10];

printf("\n Enter total Number of Verticies \n");

scanf("%d",&n);

printf("Enter Matrix for %d Verticies",n);

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

scanf("%d",&a[i][j]);

printf("\nEnter starting vertex\n");

scanf("%d",&s);

for(i=1;i<=n;i++)

cov[i]=0;

dfs(cov,s,n);

printf("The vertices reachable are\n");

for(i=1;i<=n;i++)

if(cov[i])

printf("%d\t",i);

return 0;

dfs(int cov[],int s,int n)

int i;

cov[s]=1;

Dept of MCA,RVCE 52

Page 53: Ada Lab Manual-rvce

for(i=1;i<=n;i++)

if(!cov[i] && a[s][i])

dfs(cov,i,n);

enter the number of nodes

10enter the cost adajacency matrix0 1 1 0 0 0 0 0 0 00 0 0 0 1 0 0 0 0 00 0 0 0 0 1 0 0 0 00 0 0 0 0 0 1 0 0 00 0 0 0 0 0 0 1 0 00 0 0 0 0 0 0 1 0 00 0 0 0 0 0 0 1 1 00 0 0 0 0 0 0 0 0 10 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 1 0

enter the source

1node 0 is not reachablenode 1 is reachablenode 2 is not reachablenode 3 is not reachablenode 4 is reachablenode 5 is not reachablenode 6 is not reachablenode 7 is reachablenode 8 is reachablenode 9 is reachable

the graph is not connected

Dept of MCA,RVCE 53

Page 54: Ada Lab Manual-rvce

8. Find a subset of a given set S = s1,2,…….,sn of n positive integers whose sum

is equal to a given positive integer d. for example, if S=1,2,5,6,8 and d = 9

there are two solution 1,2,6 and 1,8. A suitable message is to be displayed if

the given problem instance doesn’t have solution.

Problem: An instance of the Subset Sum problem is a pair (S, t), where S = x1 , x2 , ..., xn is a set of positive integers and t (the target) is a positive integer. The decision problem asks for a subset of S whose sum is as large as possible, but not larger than t.This problem is NP-complete.

Method:The algorithm uses backtracking method to solve the problem.

Procedure:

void sumofsubsets(int s,int k, int r) x[k]=1; if(s+w[k] == d) flag =1; printf("\n subset %d", ++count); for(i=0;i<=k;i++) if(x[i]==1) printf("%d",w[i]); else if(s+w[k] +w[k+1]<=d) sumofsubsets(s+w[k],k+1,r-w[k]); if((s+r-w[k] >=d) && (s+w[k+1]<=d)) x[k]=0; sumofsubsets(s,k+1,r-w[k]);

Source Code

#include<stdio.h>int w[10],d,n,count=0,x[10],i,flag=0;void sumofsubsets(int s,int k, int r)

Dept of MCA,RVCE 54

Page 55: Ada Lab Manual-rvce

x[k]=1; if(s+w[k] == d) flag =1; printf("\n subset %d", ++count); for(i=0;i<=k;i++) if(x[i]==1) printf("%d",w[i]); else if(s+w[k] +w[k+1]<=d) sumofsubsets(s+w[k],k+1,r-w[k]); if((s+r-w[k] >=d) && (s+w[k+1]<=d)) x[k]=0; sumofsubsets(s,k+1,r-w[k]);

int main() int s,r=0,k; printf("Enter the number of elements\n"); scanf("%d",&n); printf("Enter the elements in ascending order\n"); for(i=0;i<n;i++) scanf("%d",&w[i]); printf("Enter the sum\n"); scanf("%d",&d); for(i=0;i<n;i++) x[i]=0; for(i=0;i<n;i++) r+=w[i]; sumofsubsets(0,0,r); if(flag==0) printf("\n solution not possible\n");Enter the number of elements6Enter the elements in ascending order3 4 5 6 7 8 Enter the sum13 subset 1 3,4,6

Dept of MCA,RVCE 55

Page 56: Ada Lab Manual-rvce

subset 2 5,8 subset 3 6,7

9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation.

Problem:To find an optimal solution for the travelling salesman problem and solve the same problem instance using any approximation algorithm and determine the error in the approximation.

Method:

The travelling salesman problem can be solved using greedymethod, dynamic programming method, heuristic method etc. The approximation algorithms which can be used for travelling salesman problem includes DFS,BFS,2-opt algorithm, v-opt algorithm, LKH algorithm etc. In this problem the DFS algorithm is used and the cost is found.The same source code of DFS can be used along with the following modification :

Proceudre for finding cost using approximation is printf("Enter the cost matrix of the vertices\n");

for(i=1;i<=n;i++)

scanf ("%d",&cost[i]);

sum = sum + cost[i];

printf("the tour cost is %d",sum);

The DFS method also produces the same output. Therefore the error value is NIL.Source Code

/* C program to demonstrate travelling salesperson problem. */

Dept of MCA,RVCE 56

Page 57: Ada Lab Manual-rvce

#include <stdio.h>

#define MAX 100

#define INFINITY 999

int tsp_dp (int c[][MAX], int tour[], int start, int n);

int main()

int n; /* Number of cities. */

int i, j; /* Loop counters. */

int c[MAX][MAX]; /* Cost matrix. */

int tour[MAX]; /* Tour matrix. */

int cost; /* Least cost. */

printf ("This program demonstrates the TSP problem.");

printf ("\nHow many cities to traverse? ");

scanf ("%d", &n);

printf ("Enter the cost matrix: (999: no connection)\n");

for (i=0; i<n; i++)

for (j=0; j<n; j++)

scanf ("%d", &c[i][j]);

for (i=0; i<n; i++)

tour[i] = i;

cost = tsp_dp (c, tour, 0, n);

rintf ("Minimum cost: %d.\nTour: ", cost);

for (i=0; i<n; i++)

Dept of MCA,RVCE 57

Page 58: Ada Lab Manual-rvce

printf ("%d ", tour[i]+1);

printf ("1\n");

int tsp_dp (int c[][MAX], int tour[], int start, int n)

int i, j, k; /* Loop counters. */

int temp[MAX]; /* Temporary during calculations. */

int mintour[MAX]; /* Minimal tour array. */

int mincost; /* Minimal cost. */

int ccost; /* Current cost. */

/* End of recursion condition. */

if (start == n - 2)

return c[tour[n-2]][tour[n-1]] + c[tour[n-1]][0];

/* Compute the tour starting from the current city. */

mincost = INFINITY;

for (i = start+1; i<n; i++)

for (j=0; j<n; j++)

temp[j] = tour[j];

/* Adjust positions. */

temp[start+1] = tour[i];

temp[i] = tour[start+1];

/* Found a better cycle? (Recurrence derivable.) */

Dept of MCA,RVCE 58

Page 59: Ada Lab Manual-rvce

if (c[tour[start]][tour[i]] +

(ccost = tsp_dp (c, temp, start+1, n)) < mincost)

mincost = c[tour[start]][tour[i]] + ccost;

for (k=0; k<n; k++)

mintour[k] = temp[k];

for (i=0; i<n; i++)

tour[i] = mintour[i];

return mincost;

Travelling Salesman ProblemHow many cities to traverse? 3Enter the cost matrix: (999: no connection)999 200 400200 999 200400 200 999Minimum cost: 800.Tour: 1 2 3 1

Error approximation =0.

10. Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm.

ProblemTo find the minimum cost spanning tree of the undirected graph using prim's method.

Method:

Prims algorithm

Dept of MCA,RVCE 59

Page 60: Ada Lab Manual-rvce

It starts from an arbitrary vertex (root) and at each stage, add a new branch (edge) to the

tree already constructed; the algorithm halts when all the vertices in the graph have been

reached. This strategy is greedy in the sense that at each step the partial spanning tree is

augmented with an edge that is the smallest among all possible adjacent edges.

Analysis

The algorithm spends most of its time in finding the smallest edge. So, time of the

algorithm

Basically depends on how we search this edge. Straightforward method

Just find the smallest edge by searching the adjacency list of the vertices in V. In this case,

each iteration costs O(m) time, yielding a total running time of O(mn).

Now we describe the Prim's algorithm when the graph G =(V, E) is represented as an

adjacency matrix.

Instead of heap structure, we use an array to store the key of each node

Procedure:

A ← V[g] // Array

For each vertex uQ do

key [u] ∞

key [r] ← 0

π[r] ← NIL

while Array A empty do

scan over A find the node u with smallest key, and remove it from array A

for each vertex vÎAdj[u]

if v A and w[u, v] < key[v] then

π[v] ← u

key[v] ← w[u, v]

let T be a single vertex xwhile (T has fewer than n vertices) find the smallest edge connecting T to G-T

add it to T

Dept of MCA,RVCE 60

Page 61: Ada Lab Manual-rvce

Source Code:

#include<stdio.h>#include<stdlib.h>

#define MAX 6#define INFINITY 999

void prim(int [][MAX],int);int edge[MAX][2];

void main()

int cost[MAX][MAX], n, mincost=0, i,j;

printf("\n Enter the no of vertices:\n");scanf("%d",&n);

printf("\nEnter the Cost Adjacency Matrix for %d Verticies \n",n);printf("(enter 9999 to indicate no edge)\n");

for(i=1;i<=n;i++)for(j=1;j<=n;j++)

scanf("%d",&cost[i][j]);

printf("\nEntered Cost Adjacency Matrix as followes \n",n);

for(i=1;i<=n;i++)for(j=1;j<=n;j++)

printf("%5d",cost[i][j]);printf("\n");

prim(cost,n);

for(i=1;i<=n-1;i++)mincost+=cost[edge[i][1]][edge[i][2]];

printf("\nThe solution to MWST = %d\n",mincost);

if(mincost>=1000)

Dept of MCA,RVCE 61

Page 62: Ada Lab Manual-rvce

printf("There is no Minimum Spanning Tree\n");exit(1);

printf("\n Edges of the Minimum spanning tree\n");

for(i=1;i<=n;i++)printf("<%2d,%2d>",edge[i][1],edge[i][2]);

void prim(int cost [][MAX],int n)

int closest[MAX];int lowcost[MAX],min;int i,j,k;for(i=2;i<=n;i++)

lowcost[i]=cost[1][i];closest[i]=1;

for(i=2;i<=n;i++)

min=lowcost[2];k=2;for(j=3;j<=n;j++)if(lowcost[j]<min)

min=lowcost[j];k=j;

edge[i-1][1]=closest[k];edge[i-1][2]=k;

lowcost[k]=INFINITY;for(j=2;j<=n;j++)if(cost[k][j]<lowcost[j])if(lowcost[j]<INFINITY)

lowcost[j]=cost[k][j];closest[j]=k;

Prims Algorithm Enter the no of vertices:3

Dept of MCA,RVCE 62

Page 63: Ada Lab Manual-rvce

Enter the Cost Adjacency Matrix for 3 Verticies (enter 9999 to indicate no edge)9999 45 50 45 999 6050 60 999

Entered Cost Adjacency Matrix as follows

9999 45 50

45 999 60

50 60 999The solution to MWST = 95

11. Implement Floyd’s algorithm for the All-pairs-Shortest-Paths Problem. Parallelize this algorithm, implement using OpenMP and determine the speed up achieved.

Problem:

To find the shortest path for all the pairs of the graph using floyds algorithm and implement openMP method to parallelize the algorithm.

Method:

OpenMP Methods:

1. #include<omp.h> : It is the header file which should be used to implement the functions using open MP

2.#pragma omp parallel private(var1, var2) shared(var3)

Parallel section executed by all threads . . .

All threads join master thread and disband

This section is used to parallelize all the sections using threds.

Dept of MCA,RVCE 63

Page 64: Ada Lab Manual-rvce

3. #pragma omp for nowait : Helps to parallely run the for loops

Execution : To execute programs using open MP concepts the command is

gcc -fopenmp filename.c

Procedure:

allpairs(cost,a,n);

printf("\n The shortest path matrix obtained is as followes \n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

printf("%3d",a[i][j]);

printf("\n");

void allpairs(int c[][MAX],int a[][MAX],int n)

int s,i,j,k;

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

if (i==j)

a[i][j]=0;

else

a[i][j]=c[i][j];

for(k=1;k<=n;k++)

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

Dept of MCA,RVCE 64

Page 65: Ada Lab Manual-rvce

a[i][j]=min(a[i][j],a[i][k]+a[k][j]);

Source Code:

#include<stdio.h>

#include<sys/time.h>

#define TRUE 1

#define MAX 10

#define INFINITY 999

struct Timer

int time;

mytimer;

void allpairs(int [][MAX],int [][MAX],int);

int min(int,int);

void main()

int cost[MAX][MAX];

int a[MAX][MAX];

int n;

int i,j;

struct timeval st,en;

printf("Enter the no of vertices:");

scanf("%d",&n);

Dept of MCA,RVCE 65

Page 66: Ada Lab Manual-rvce

printf("Vertices Considered : %d ",n);

printf("\nEnter the cost adjacency matrix\n and 999 for no cost\n ");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

scanf("%d",&cost[i][j]);

printf("\nEntered cost adjacency Matrix as follows \n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

printf(" %3d ",cost[i][j]);

printf("\n");

gettimeofday(&st,0);

allpairs(cost,a,n);

gettimeofday(&en,0);

mytimer.time=(en.tv_usec-st.tv_usec);

printf("the time taken is %d micro seconds",mytimer.time);

printf("\n The shortest path matrix obtained is as followes \n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

printf("%3d",a[i][j]);

Dept of MCA,RVCE 66

Page 67: Ada Lab Manual-rvce

printf("\n");

void allpairs(int c[][MAX],int a[][MAX],int n)

int s,i,j,k;

#pragma omp parallel shared(n,a,c,nthreads) private(i,tid)

tid = omp_get_thread_num();

/* Only master thread does this */

if (tid == 0)

nthreads = omp_get_num_threads();

printf("Number of threads = %d\n", nthreads);

#pragma omp for nowait

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

if (i==j)

a[i][j]=0;

else

a[i][j]=c[i][j];

Dept of MCA,RVCE 67

Page 68: Ada Lab Manual-rvce

for(k=1;k<=n;k++)

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

a[i][j]=min(a[i][j],a[i][k]+a[k][j]);

exit(0);

int min(int a,int b)

return(a<b)?a:b;

Enter the no of vertices:4

Vertices Considered : 4

Enter the cost adjacency matrix

Enter 999 for no cost

999 999 3 999

2 999 999 999

999 7 999 1

6 999 999 999

Entered cost adjacency Matrix as follows

999 999 3 999

2 999 999 999

999 7 999 1

Dept of MCA,RVCE 68

Page 69: Ada Lab Manual-rvce

6 999 999 999

The time taken is 4 micro seconds

The shortest Path obtained is :

0 10 3 4

2 0 5 6

7 7 0 1

6 16 9 0

No.of threads=4

12.Implement N Queen’s problem using Back Tracking

Problem The n-queens problem is to place n queens on an n-by-n chessboard so that no two

queens attach each other by being in the same row or in the same column or on the same diagonal.s

Method:The method applied to solve the problem is Backtracking. The principal idea is to

construct solutions one component at a time and evaluate such partially constructed candidates. If a partially constructed solution can be developed further without violating the problem’s constraints, it is done by taking trhe first remaining legitimate option for the next component. If there is not legitimate option for the next component, no alternatives for any remaining component need to be considered. In this case, the algorithm backtracks to replace the last component fo the partially constructed solution with its next option.

Procedure:

void nqueens(int x[],int n)

int k;x[0]=-1;k=0;

while(k>=0)

x[k]=x[k]+1;while(x[k]<n && !place(x,k))

Dept of MCA,RVCE 69

Page 70: Ada Lab Manual-rvce

x[k]=x[k]+1;if(x[k]<n)if(k==n-1)

display(x,n);return;

Source Code:

#include<stdio.h>#include<math.h>

#define MAX 20#define TRUE 1#define FALSE 0

void display(int [],int);void nqueens(int [],int);int place(int [],int);

void main()

int x[MAX];int i,j,n;

printf("Enter the number of queens:");scanf("%d",&n);if(n>=3)

printf("The solution to %d Queens problem is:\n",n);nqueens(x,n);

elseprintf("Number of queens should be greater than 3\n");

void nqueens(int x[],int n)

int k;x[0]=-1;k=0;

while(k>=0)

Dept of MCA,RVCE 70

Page 71: Ada Lab Manual-rvce

x[k]=x[k]+1;while(x[k]<n && !place(x,k)) x[k]=x[k]+1;if(x[k]<n)if(k==n-1)

display(x,n);return;

else

k++;x[k]=-1;

elsek--;

int place(int x[],int k)

int i;for(i=0;i<k;i++)if(x[i]==x[k] || (abs(x[i]-x[k])==abs(i-k)))return (FALSE);return (TRUE);

void display(int x[],int n)

int s[MAX][MAX];int i,j;

for(i=0;i<n;i++)for(j=0;j<n;j++)s[i][j]=0;

for(i=0;i<n;i++)s[i][x[i]]=TRUE;

for(i=0;i<n;i++)

for(j=0;j<n;j++)printf(" %d ",s[i][j]);printf("\n");

Dept of MCA,RVCE 71

Page 72: Ada Lab Manual-rvce

Enter the number of queens:4

The solution to 4 Queens problem is:

0 1 0 0

0 0 0 1

1 0 0 0

0 0 1 0

Dept of MCA,RVCE 72

Page 73: Ada Lab Manual-rvce

EXTRA QUESTIONS

1. Write a program to implement linear search using c++

2. Implement binary search and analyse the efficiency of the algorithm

3. Implement strassen matrix multiplication using divide and conquer method

4. Implement graph coloring algorithm using backtracking method

5. Implement kanpsack problem using backtracking method in c++.

6. Write a program to sort a given set of numbers using heap sort in c++. The

numbers should be read from a file.

7. Write a program to implement horsepool algorithm in c++

8. Implement binomial co-efficient using c++

9. Write a program to implement linear search and find the speed of the algorithm

10. Write a program to implement dijkstra’s algorithm

Dept of MCA,RVCE 73

Page 74: Ada Lab Manual-rvce

VIVA QUESTIONS1. Define an algorithm

2. Define recursion

3. Mention the different types of order of growth?

4. Define Ω notation

5. Define time complexity

6. Define space complexity

7. What are the factors on which the time efficiency of an algorithm depend

8. Explain how do we implement time in c and c++.

9. What are the different methodologies applied in finding the efficiency of an algorithm

10. Explain Quick sort method

11. What is open MP

12. What is the header file used to work on open MP

13. What are the various steps in which a program can be parallelized.

14. Differentiate omp for nowait and section nowait

15. What is order of growth of merge sort

16. What do you mean by topological ordering

17. What do you mean by mean by All-pairs shortest path problem?

18. What do you mean by dynamic programming

19. What is the difference between dynamic programming and divide and conquer

20. What is knapsack problem?

21. What is Dijkstra’s algorithm?

22. Whether Dijkstra’s can be implemented for directed graph

23. What do you mean by Spanning tree?

24. What is order of growth of quick sort

25. What is the difference between Prim’s and Kruskal algorithm

26. Which is the best sorting technique and why?

27. What is the difference between directed and undirected graph

28. What is the difference between Floyd’s and Dijkstra’s algorithm

29. What do you mean by DFS

30. What do you mean by BFS

Dept of MCA,RVCE 74

Page 75: Ada Lab Manual-rvce

31. What do you mean by transitive closure of a given graph?

32. How do you get the transitive closure of a given graph using Warshall’s algorithm

33. What do you mean by queen’s problem?

34. What is the difference between branch and bound and backtracking?

35. What is the difference between NP and NP-hard problems

36. What is the difference between p and NP problems

37. What do you mean by subset problem?

38. What do you mean by graph problems

39. What do you mean by exhaustive search problem

40. Write down the order of growth depending upon their efficiencies

41. What is travelling salesman problem.

42. What are the various methods that can be implemented to solve travelling salesman problem

43. What is approximation algorithm

44. Define topological sorting.

45. What are the applications of travelling salesman problem

46. Where do we apply topological sorting.

47. Define horsepool problem

48. What is an approximate solution

49. How do we find the error in approximation

50. Give the difference between kruskal’s method and prim’s method.

Dept of MCA,RVCE 75

Page 76: Ada Lab Manual-rvce

R.V.COLLEGE OF ENGINEERING

DEPARTMENTOF M.C.A

10MCA 48 ALGORTIHMS LABORATORY

Lab Cycle 1:

Sort a given set of elements using the Quick sort method and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator.

Lab Cycle 2:

Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and determine the time required to sort the elements. Repeat the experiment for different values of n, the number of elements in the list to be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be generated using the random number generator.

Lab Cycle 3

3a. Obtain the Topological ordering of vertices in a given digraph.

3b. Compute the transitive closure of a given directed graph using Warshall's algorithm Lab Cycle 4:

4. Implement 0/1 Knapsack problem using Dynamic Programming.

5 . From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm

Lab Cycle 5:

6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.

Lab Cycle 6:

7. a. Print all the nodes reachable from a given starting node in a digraph using BFS method.

b. Check whether a given graph is connected or not using DFS method.

Dept of MCA,RVCE 76

Page 77: Ada Lab Manual-rvce

Lab Cycle 7:

8. Find a subset of a given set S = sl,s2,.....,sn of n positive integers whose sum is equal to a given positive integer d. For example, if S= 1, 2, 5, 6, 8 and d = 9 there are two solutions1,2,6and1,8.A suitable message is to be displayed if the given problem instance doesn't have a solution.

Lab Cycle 8:

9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then solve the same problem instance using any approximation algorithm and determine the error in the approximation.

10. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.

Lab Cycle 9:

11. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved.

12. Implement N Queen's problem using Back Tracking.

Lab Cycle 10: Backlogs if any.

Instructions:

Students are required to write the aim, program in c/c++ and three inputs in the data sheet. They are also required to bring graph sheets whenever necessary.

Procedure for writing record:

Left Hand Side:

1. A short description about the program

2. Pseudocode of the program

3. Input and Output.

Right Hand Side:

1. Program

Evaluation in the Lab: 7 marks – Execution and 3 marks for Viva

Dept of MCA,RVCE 77