rguLAB

DAA Lab: all codes + viva

27 record programs. Copy any code; the output and viva answers are right below it.

Download PDF

Searching

Program 01

Linear search

Write a program in c to search an element using linear search and find its execution time using the time function.

Run it

Algorithm

Algorithm: LinearSearch(A, n, x)

1. Start
2. For i <- 0 to (n-1) do
3.        if x == A[i] then
4.              print "Element Found"
5.              exit
6. If (i==n) then
7.         print "Element Not Found"
8. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,x,count=0;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Enter the element to search:");
    scanf("%d",&x);

    clock_t start=clock();
    for(i=0;i<n;i++) {
        count++;
        if(x==a[i])
            break;
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    if(i==n)
        printf("\n%d is not found",x);
    else
        printf("\n%d is found at position %d",x,i+1);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: best case O(1), worst case O(n)");
    printf("\nSpace complexity: O(1)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 14 27 8 35 19 42 ⏎ 35

Enter the number of elements:6
Enter the elements:14 27 8 35 19 42
Enter the element to search:35

35 is found at position 4
Number of comparisons:4
Time taken:0.000003 seconds
Time complexity: best case O(1), worst case O(n)
Space complexity: O(1)

Complexity

Time complexity: best case O(1), worst case O(n)
Space complexity: O(1)
Best caseO(1)
Average caseO(n)
Worst caseO(n)
ParadigmBrute force

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,x,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  3. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  6. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  9. printf("Enter the element to search:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  10. scanf("%d",&x);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  11. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  12. for(i=0;i<n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  13. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  14. if(x==a[i])

    This line is a decision. if runs the block only when the condition is true.

  15. break;

    break leaves the nearest loop (or switch) immediately.

  16. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  17. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  18. if(i==n)

    This line is a decision. if runs the block only when the condition is true. n is the number of elements (or processes).

  19. printf("\n%d is not found",x);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  20. printf("\n%d is found at position %d",x,i+1);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  21. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  22. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  23. printf("\nTime complexity: best case O(1), worst case O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  24. printf("\nSpace complexity: O(1)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  25. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  26. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Linear search?

A. Best O(1), average O(n), worst O(n). Design paradigm: Brute force.

Q. Linear search's best case happens when…

A. The key is the first element. One comparison, so O(1).

Q. Does linear search need a sorted array?

A. No, it works on any order. Binary search is the one that needs sorted input.

Program 02

Binary search

Write a program in c to search an element using binary search and find its execution time using the time function.

Run it

Algorithm

Algorithm: BinarySearch(A, n, x)

1. Start
2. low <- 0, high <- (n-1)
3. While (low <= high) do
4.        mid <- (low+high)/2
5.        if x == A[mid] then
6.              print "Element Found"
7.              exit
8.        else if A[mid] < x then
9.              low <- mid+1
10.       else
11.             high <- mid-1
12. If (low > high) then
13.        print "Element Not Found"
14. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,x,low,high,mid,count=0;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements in ascending order:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("Enter the element to search:");
    scanf("%d",&x);

    clock_t start=clock();
    low=0;
    high=n-1;
    while(low<=high) {
        count++;
        mid=(low+high)/2;
        if(x==a[mid])
            break;
        else if(a[mid]<x)
            low=mid+1;
        else
            high=mid-1;
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    if(low>high)
        printf("\n%d is not found",x);
    else
        printf("\n%d is found at position %d",x,mid+1);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: best case O(1), worst case O(log n)");
    printf("\nSpace complexity: O(1)");
    printf("\n");
    return 0;
}

Output

Input typed: 7 ⏎ 8 14 19 27 35 42 56 ⏎ 42

Enter the number of elements:7
Enter the elements in ascending order:8 14 19 27 35 42 56
Enter the element to search:42

42 is found at position 6
Number of comparisons:2
Time taken:0.000005 seconds
Time complexity: best case O(1), worst case O(log n)
Space complexity: O(1)

Complexity

Time complexity: best case O(1), worst case O(log n)
Space complexity: O(1)
Best caseO(1)
Average caseO(log n)
Worst caseO(log n)
ParadigmDivide & conquer

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,x,low,high,mid,count=0;

    Declares the variables used below. n is the number of elements (or processes). low is the left end of the current search or sort range.

  3. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  6. printf("Enter the elements in ascending order:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  9. printf("Enter the element to search:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  10. scanf("%d",&x);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  11. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  12. low=0;

    low is the left end of the current search or sort range.

  13. high=n-1;

    high is the right end of the current range. n is the number of elements (or processes).

  14. while(low<=high) {

    This line is a while loop. while (condition) repeats as long as the condition is true. low is the left end of the current search or sort range.

  15. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  16. mid=(low+high)/2;

    mid = (low + high) / 2 splits the range in half. low is the left end of the current search or sort range. high is the right end of the current range.

  17. if(x==a[mid])

    This line is a decision. if runs the block only when the condition is true. mid = (low + high) / 2 splits the range in half.

  18. break;

    break leaves the nearest loop (or switch) immediately.

  19. else if(a[mid]<x)

    This line is a decision. else runs when the if condition was false. if runs the block only when the condition is true.

  20. low=mid+1;

    low is the left end of the current search or sort range. mid = (low + high) / 2 splits the range in half.

  21. high=mid-1;

    high is the right end of the current range. mid = (low + high) / 2 splits the range in half.

  22. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  23. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  24. if(low>high)

    This line is a decision. if runs the block only when the condition is true. low is the left end of the current search or sort range.

  25. printf("\n%d is not found",x);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  26. printf("\n%d is found at position %d",x,mid+1);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). mid = (low + high) / 2 splits the range in half.

  27. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  28. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  29. printf("\nTime complexity: best case O(1), worst case O(log n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  30. printf("\nSpace complexity: O(1)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  31. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  32. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Binary search?

A. Best O(1), average O(log n), worst O(log n). Design paradigm: Divide & conquer.

Q. Binary search requires…

A. A sorted array. It discards half of the range each step.

Q. mid is computed as…

A. low + (high − low) / 2. That form avoids integer overflow of (low + high).

Q. Maximum comparisons for n = 1024 is about…

A. 11. ⌊log₂ 1024⌋ + 1 = 11.

Sorting

Program 03

Bubble sort

Write a program in c to sort the elements using bubble sort and find its execution time using the time function.

Run it

Algorithm

Algorithm: BubbleSort(A, n)

1. Start
2. For i <- 0 to (n-2) do
3.        For j <- 0 to (n-i-2) do
4.              if A[j] > A[j+1] then
5.                    temp <- A[j]
6.                    A[j] <- A[j+1]
7.                    A[j+1] <- temp
8. Print the sorted array A
9. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,j,temp,count=0;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    clock_t start=clock();
    for(i=0;i<n-1;i++) {
        for(j=0;j<n-i-1;j++) {
            count++;
            if(a[j]>a[j+1]) {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nAfter bubble sorting:");
    for(i=0;i<n;i++)
        printf("\t%d",a[i]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n^2)");
    printf("\nSpace complexity: O(1)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 42 8 27 14 35 19

Enter the number of elements:6
Enter the elements:42 8 27 14 35 19

After bubble sorting:	8	14	19	27	35	42
Number of comparisons:15
Time taken:0.000005 seconds
Time complexity: O(n^2)
Space complexity: O(1)

Complexity

Time complexity: O(n^2)
Space complexity: O(1)
Best caseO(n²)
Average caseO(n²)
Worst caseO(n²)
ParadigmBrute force

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,j,temp,count=0;

    Declares the variables used below. n is the number of elements (or processes). temp holds one value while two are swapped.

  3. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  6. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  9. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  11. for(j=0;j<n-i-1;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  12. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  13. if(a[j]>a[j+1]) {

    This line is a decision. if runs the block only when the condition is true.

  14. temp=a[j];

    Part of a swap: temp holds one value while the two are exchanged. temp holds one value while two are swapped.

  15. a[j]=a[j+1];

    a is the array being searched or sorted.

  16. a[j+1]=temp;

    a is the array being searched or sorted. temp holds one value while two are swapped.

  17. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  18. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  19. printf("\nAfter bubble sorting:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  21. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  22. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  23. printf("\nTime complexity: O(n^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  24. printf("\nSpace complexity: O(1)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  25. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  26. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Bubble sort?

A. Best O(n²), average O(n²), worst O(n²). Design paradigm: Brute force.

Q. After pass 1 of bubble sort, where is the largest element?

A. At the end of the array. Big values 'bubble' to the right.

Q. How can bubble sort reach O(n) on sorted input?

A. Stop when a pass makes no swaps (swapped flag). This version always runs every pass, so it stays O(n²).

Q. Comparisons made for n = 6 are…

A. 15. n(n − 1) / 2 = 15.

Program 04

Selection sort

Write a program in c to sort the elements using selection sort and find its execution time using the time function.

Run it

Algorithm

Algorithm: SelectionSort(A, n)

1. Start
2. For i <- 0 to (n-2) do
3.        min <- i
4.        For j <- i+1 to (n-1) do
5.              if A[j] < A[min] then
6.                    min <- j
7.        temp <- A[i]
8.        A[i] <- A[min]
9.        A[min] <- temp
10. Print the sorted array A
11. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,j,min,temp,count=0;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    clock_t start=clock();
    for(i=0;i<n-1;i++) {
        min=i;
        for(j=i+1;j<n;j++) {
            count++;
            if(a[j]<a[min])
                min=j;
        }
        temp=a[i];
        a[i]=a[min];
        a[min]=temp;
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nAfter selection sorting:");
    for(i=0;i<n;i++)
        printf("\t%d",a[i]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n^2)");
    printf("\nSpace complexity: O(1)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 42 8 27 14 35 19

Enter the number of elements:6
Enter the elements:42 8 27 14 35 19

After selection sorting:	8	14	19	27	35	42
Number of comparisons:15
Time taken:0.000006 seconds
Time complexity: O(n^2)
Space complexity: O(1)

Complexity

Time complexity: O(n^2)
Space complexity: O(1)
Best caseO(n²)
Average caseO(n²)
Worst caseO(n²)
ParadigmBrute force

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,j,min,temp,count=0;

    Declares the variables used below. n is the number of elements (or processes). min tracks the smallest value (or its index) found so far.

  3. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  6. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  9. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  11. min=i;

    min tracks the smallest value (or its index) found so far.

  12. for(j=i+1;j<n;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  13. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  14. if(a[j]<a[min])

    This line is a decision. if runs the block only when the condition is true. min tracks the smallest value (or its index) found so far.

  15. min=j;

    min tracks the smallest value (or its index) found so far.

  16. temp=a[i];

    Part of a swap: temp holds one value while the two are exchanged. temp holds one value while two are swapped.

  17. a[i]=a[min];

    a is the array being searched or sorted. min tracks the smallest value (or its index) found so far.

  18. a[min]=temp;

    a is the array being searched or sorted. min tracks the smallest value (or its index) found so far. temp holds one value while two are swapped.

  19. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  20. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  21. printf("\nAfter selection sorting:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  23. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  24. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  25. printf("\nTime complexity: O(n^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  26. printf("\nSpace complexity: O(1)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  27. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  28. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Selection sort?

A. Best O(n²), average O(n²), worst O(n²). Design paradigm: Brute force.

Q. Selection sort makes at most how many swaps?

A. n − 1. One swap per pass: useful when writing to memory is expensive.

Q. Is selection sort stable?

A. No, the long-distance swap can reorder equal keys. Insertion sort and merge sort are stable.

Program 05

Insertion sort

Write a program in c to sort the elements using insertion sort and find its execution time using the time function.

Run it

Algorithm

Algorithm: InsertionSort(A, n)

1. Start
2. For i <- 1 to (n-1) do
3.        key <- A[i]
4.        j <- i-1
5.        While (j >= 0 and A[j] > key) do
6.              A[j+1] <- A[j]
7.              j <- j-1
8.        A[j+1] <- key
9. Print the sorted array A
10. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,j,key,count=0;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    clock_t start=clock();
    for(i=1;i<n;i++) {
        key=a[i];
        j=i-1;
        while(j>=0) {
            count++;
            if(a[j]>key) {
                a[j+1]=a[j];
                j--;
            }
            else
                break;
        }
        a[j+1]=key;
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nAfter insertion sorting:");
    for(i=0;i<n;i++)
        printf("\t%d",a[i]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: best case O(n), worst case O(n^2)");
    printf("\nSpace complexity: O(1)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 42 8 27 14 35 19

Enter the number of elements:6
Enter the elements:42 8 27 14 35 19

After insertion sorting:	8	14	19	27	35	42
Number of comparisons:12
Time taken:0.000005 seconds
Time complexity: best case O(n), worst case O(n^2)
Space complexity: O(1)

Complexity

Time complexity: best case O(n), worst case O(n^2)
Space complexity: O(1)
Best caseO(n)
Average caseO(n²)
Worst caseO(n²)
ParadigmIncremental

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,j,key,count=0;

    Declares the variables used below. n is the number of elements (or processes). key is the value being searched for, or the element being inserted.

  3. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  6. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  9. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  10. for(i=1;i<n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  11. key=a[i];

    key is the value being searched for, or the element being inserted.

  12. j=i-1;

    j is the inner loop counter.

  13. while(j>=0) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  14. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  15. if(a[j]>key) {

    This line is a decision. if runs the block only when the condition is true. key is the value being searched for, or the element being inserted.

  16. a[j+1]=a[j];

    a is the array being searched or sorted.

  17. j--;

    j is the inner loop counter.

  18. break;

    break leaves the nearest loop (or switch) immediately.

  19. a[j+1]=key;

    a is the array being searched or sorted. key is the value being searched for, or the element being inserted.

  20. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  21. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  22. printf("\nAfter insertion sorting:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  24. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  25. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  26. printf("\nTime complexity: best case O(n), worst case O(n^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  27. printf("\nSpace complexity: O(1)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  28. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  29. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Insertion sort?

A. Best O(n), average O(n²), worst O(n²). Design paradigm: Incremental.

Q. Insertion sort's best case is…

A. An already sorted array: O(n). Each new key is compared once and stays put.

Q. Insertion sort is like…

A. Sorting playing cards in your hand. Take the next card and slide it left into place.

Program 06

Radix sort

Write a program in c to sort the elements using radix sort and find its execution time using the time function.

Run it

Algorithm

Algorithm: RadixSort(A, n)

1. Start
2. max <- largest element of A
3. exp <- 1
4. While (max/exp > 0) do
5.        CountSort(A, n, exp)
6.        exp <- exp*10
7. Print the sorted array A
8. Stop

Algorithm: CountSort(A, n, exp)

1. For i <- 0 to 9 do
2.        bucket[i] <- 0
3. For i <- 0 to (n-1) do
4.        d <- (A[i]/exp) mod 10
5.        bucket[d] <- bucket[d]+1
6. For i <- 1 to 9 do
7.        bucket[i] <- bucket[i]+bucket[i-1]
8. For i <- (n-1) down to 0 do
9.        d <- (A[i]/exp) mod 10
10.       bucket[d] <- bucket[d]-1
11.       output[bucket[d]] <- A[i]
12. For i <- 0 to (n-1) do
13.       A[i] <- output[i]
14. Return

Program

#include<stdio.h>
#include<time.h>

int count=0;

void countSort(int a[],int n,int exp) {
    int output[n],bucket[10],i;

    for(i=0;i<10;i++)
        bucket[i]=0;
    for(i=0;i<n;i++) {
        count++;
        bucket[(a[i]/exp)%10]++;
    }
    for(i=1;i<10;i++)
        bucket[i]=bucket[i]+bucket[i-1];
    for(i=n-1;i>=0;i--) {
        count++;
        output[--bucket[(a[i]/exp)%10]]=a[i];
    }
    for(i=0;i<n;i++)
        a[i]=output[i];
}

int main() {
    int n,i,max,exp;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    clock_t start=clock();
    max=a[0];
    for(i=1;i<n;i++)
        if(a[i]>max)
            max=a[i];
    for(exp=1;max/exp>0;exp=exp*10)
        countSort(a,n,exp);
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nAfter radix sorting:");
    for(i=0;i<n;i++)
        printf("\t%d",a[i]);
    printf("\nNumber of operations:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(d*n)");
    printf("\nSpace complexity: O(n+k)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 42 8 27 14 35 19

Enter the number of elements:6
Enter the elements:42 8 27 14 35 19

After radix sorting:	8	14	19	27	35	42
Number of operations:24
Time taken:0.000009 seconds
Time complexity: O(d*n)
Space complexity: O(n+k)

Complexity

Time complexity: O(d*n)
Space complexity: O(n+k)
Best caseO(d·n)
Average caseO(d·n)
Worst caseO(d·n)
ParadigmNon-comparison

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int count=0;

    Declares the variables used below. count tallies the basic operations (comparisons/steps) to show the complexity.

  2. void countSort(int a[],int n,int exp) {

    This line defines a function. countSort() is the stable counting sort used for each radix digit. n is the number of elements (or processes).

  3. int output[n],bucket[10],i;

    Declares the variables used below. output is the temporary array the sorted pass is written into. n is the number of elements (or processes).

  4. for(i=0;i<10;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  5. bucket[i]=0;

    bucket groups values by digit (radix) or by range (bucket sort).

  6. for(i=0;i<n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  7. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  8. bucket[(a[i]/exp)%10]++;

    bucket groups values by digit (radix) or by range (bucket sort). exp is the digit place (1, 10, 100…) radix sort is sorting on.

  9. for(i=1;i<10;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  10. bucket[i]=bucket[i]+bucket[i-1];

    bucket groups values by digit (radix) or by range (bucket sort).

  11. for(i=n-1;i>=0;i--) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  12. output[--bucket[(a[i]/exp)%10]]=a[i];

    output is the temporary array the sorted pass is written into. bucket groups values by digit (radix) or by range (bucket sort). exp is the digit place (1, 10, 100…) radix sort is sorting on.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  14. a[i]=output[i];

    a is the array being searched or sorted. output is the temporary array the sorted pass is written into.

  15. int main() {

    This line defines a function. main() is where the program starts running.

  16. int n,i,max,exp;

    Declares the variables used below. n is the number of elements (or processes). max tracks the largest value found so far.

  17. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  18. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  19. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  20. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  22. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  23. max=a[0];

    max tracks the largest value found so far.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  25. if(a[i]>max)

    This line is a decision. if runs the block only when the condition is true. max tracks the largest value found so far.

  26. max=a[i];

    max tracks the largest value found so far.

  27. for(exp=1;max/exp>0;exp=exp*10)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. exp is the digit place (1, 10, 100…) radix sort is sorting on.

  28. countSort(a,n,exp);

    countSort() is the stable counting sort used for each radix digit. n is the number of elements (or processes). exp is the digit place (1, 10, 100…) radix sort is sorting on.

  29. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  30. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  31. printf("\nAfter radix sorting:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  33. printf("\nNumber of operations:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  34. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  35. printf("\nTime complexity: O(d*n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  36. printf("\nSpace complexity: O(n+k)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  37. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  38. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Radix sort?

A. Best O(d·n), average O(d·n), worst O(d·n). Design paradigm: Non-comparison.

Q. Radix sort sorts by…

A. One digit at a time, least significant digit first. Each pass uses a stable counting sort on one digit.

Q. Why must each digit pass be stable?

A. To keep the order from the earlier digit passes. Otherwise the earlier passes' work would be lost.

Program 07

Bucket sort

Write a program in c to sort the elements using bucket sort and find its execution time using the time function.

Run it

Algorithm

Algorithm: BucketSort(A, n)

1. Start
2. max <- largest element of A
3. For i <- 0 to (n-1) do
4.        size[i] <- 0
5. For i <- 0 to (n-1) do
6.        index <- (A[i]*n)/(max+1)
7.        bucket[index][size[index]] <- A[i]
8.        size[index] <- size[index]+1
9. For i <- 0 to (n-1) do
10.       sort bucket[i] using insertion sort
11. k <- 0
12. For i <- 0 to (n-1) do
13.       For j <- 0 to (size[i]-1) do
14.             A[k] <- bucket[i][j]
15.             k <- k+1
16. Print the sorted array A
17. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,j,k,key,index,max,count=0;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    clock_t start=clock();
    max=a[0];
    for(i=1;i<n;i++)
        if(a[i]>max)
            max=a[i];

    int bucket[n][n],size[n];
    for(i=0;i<n;i++)
        size[i]=0;

    for(i=0;i<n;i++) {
        index=(a[i]*n)/(max+1);
        bucket[index][size[index]++]=a[i];
    }

    for(i=0;i<n;i++) {
        for(j=1;j<size[i];j++) {
            key=bucket[i][j];
            k=j-1;
            while(k>=0) {
                count++;
                if(bucket[i][k]>key) {
                    bucket[i][k+1]=bucket[i][k];
                    k--;
                }
                else
                    break;
            }
            bucket[i][k+1]=key;
        }
    }

    k=0;
    for(i=0;i<n;i++)
        for(j=0;j<size[i];j++)
            a[k++]=bucket[i][j];
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nAfter bucket sorting:");
    for(i=0;i<n;i++)
        printf("\t%d",a[i]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: average O(n+k), worst O(n^2)");
    printf("\nSpace complexity: O(n^2)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 42 8 27 14 35 19

Enter the number of elements:6
Enter the elements:42 8 27 14 35 19

After bucket sorting:	8	14	19	27	35	42
Number of comparisons:1
Time taken:0.000002 seconds
Time complexity: average O(n+k), worst O(n^2)
Space complexity: O(n^2)

Complexity

Time complexity: average O(n+k), worst O(n^2)
Space complexity: O(n^2)
Best caseO(n+k)
Average caseO(n+k)
Worst caseO(n²)
ParadigmDistribution

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,j,k,key,index,max,count=0;

    Declares the variables used below. n is the number of elements (or processes). key is the value being searched for, or the element being inserted.

  3. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  6. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  9. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  10. max=a[0];

    max tracks the largest value found so far.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  12. if(a[i]>max)

    This line is a decision. if runs the block only when the condition is true. max tracks the largest value found so far.

  13. max=a[i];

    max tracks the largest value found so far.

  14. int bucket[n][n],size[n];

    Declares the variables used below. bucket groups values by digit (radix) or by range (bucket sort). n is the number of elements (or processes).

  15. size[i]=0;

    size is the number of elements.

  16. for(i=0;i<n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  17. index=(a[i]*n)/(max+1);

    index is the position being worked on. n is the number of elements (or processes). max tracks the largest value found so far.

  18. bucket[index][size[index]++]=a[i];

    bucket groups values by digit (radix) or by range (bucket sort). index is the position being worked on. size is the number of elements.

  19. for(j=1;j<size[i];j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. size is the number of elements.

  20. key=bucket[i][j];

    key is the value being searched for, or the element being inserted. bucket groups values by digit (radix) or by range (bucket sort).

  21. k=j-1;

    j is the inner loop counter.

  22. while(k>=0) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  23. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  24. if(bucket[i][k]>key) {

    This line is a decision. if runs the block only when the condition is true. bucket groups values by digit (radix) or by range (bucket sort).

  25. bucket[i][k+1]=bucket[i][k];

    bucket groups values by digit (radix) or by range (bucket sort).

  26. break;

    break leaves the nearest loop (or switch) immediately.

  27. bucket[i][k+1]=key;

    bucket groups values by digit (radix) or by range (bucket sort). key is the value being searched for, or the element being inserted.

  28. for(j=0;j<size[i];j++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. size is the number of elements.

  29. a[k++]=bucket[i][j];

    a is the array being searched or sorted. bucket groups values by digit (radix) or by range (bucket sort).

  30. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  31. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  32. printf("\nAfter bucket sorting:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  34. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  35. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  36. printf("\nTime complexity: average O(n+k), worst O(n^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  37. printf("\nSpace complexity: O(n^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  38. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  39. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Bucket sort?

A. Best O(n+k), average O(n+k), worst O(n²). Design paradigm: Distribution.

Q. Bucket sort is fastest when the input is…

A. Uniformly spread across the range. If everything lands in one bucket it degrades to the inner sort, O(n²).

Program 08

Quick sort

Write a program in c to sort the elements using quick sort and find its execution time using the time function.

Run it

Algorithm

Algorithm: QuickSort(A, low, high)

1. Start
2. If (low < high) then
3.        p <- Partition(A, low, high)
4.        QuickSort(A, low, p-1)
5.        QuickSort(A, p+1, high)
6. Stop

Algorithm: Partition(A, low, high)

1. pivot <- A[high]
2. i <- low-1
3. For j <- low to (high-1) do
4.        if A[j] <= pivot then
5.              i <- i+1
6.              swap A[i] and A[j]
7. swap A[i+1] and A[high]
8. Return i+1

Program

#include<stdio.h>
#include<time.h>

int count=0;

int partition(int a[],int low,int high) {
    int pivot=a[high];
    int i=low-1,j,temp;

    for(j=low;j<high;j++) {
        count++;
        if(a[j]<=pivot) {
            i++;
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
        }
    }
    temp=a[i+1];
    a[i+1]=a[high];
    a[high]=temp;
    return i+1;
}

void quickSort(int a[],int low,int high) {
    if(low<high) {
        int p=partition(a,low,high);
        quickSort(a,low,p-1);
        quickSort(a,p+1,high);
    }
}

int main() {
    int n,i;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    clock_t start=clock();
    quickSort(a,0,n-1);
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nAfter quick sorting:");
    for(i=0;i<n;i++)
        printf("\t%d",a[i]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n log n) average, O(n^2) worst");
    printf("\nSpace complexity: O(log n) average, O(n) worst");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 42 8 27 14 35 19

Enter the number of elements:6
Enter the elements:42 8 27 14 35 19

After quick sorting:	8	14	19	27	35	42
Number of comparisons:9
Time taken:0.000006 seconds
Time complexity: O(n log n) average, O(n^2) worst
Space complexity: O(log n) average, O(n) worst

Complexity

Time complexity: O(n log n) average, O(n^2) worst
Space complexity: O(log n) average, O(n) worst
Best caseO(n log n)
Average caseO(n log n)
Worst caseO(n²)
ParadigmDivide & conquer

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int count=0;

    Declares the variables used below. count tallies the basic operations (comparisons/steps) to show the complexity.

  2. int partition(int a[],int low,int high) {

    This line defines a function. partition() puts smaller elements left of the pivot and larger ones right. low is the left end of the current search or sort range.

  3. int pivot=a[high];

    Declares the variables used below. pivot is the element partition() places in its final sorted position. high is the right end of the current range.

  4. int i=low-1,j,temp;

    Declares the variables used below. low is the left end of the current search or sort range. temp holds one value while two are swapped.

  5. for(j=low;j<high;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. low is the left end of the current search or sort range.

  6. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  7. if(a[j]<=pivot) {

    This line is a decision. if runs the block only when the condition is true. pivot is the element partition() places in its final sorted position.

  8. i++;

    i is the loop counter.

  9. temp=a[i];

    Part of a swap: temp holds one value while the two are exchanged. temp holds one value while two are swapped.

  10. a[i]=a[j];

    a is the array being searched or sorted.

  11. a[j]=temp;

    a is the array being searched or sorted. temp holds one value while two are swapped.

  12. temp=a[i+1];

    Part of a swap: temp holds one value while the two are exchanged. temp holds one value while two are swapped.

  13. a[i+1]=a[high];

    a is the array being searched or sorted. high is the right end of the current range.

  14. a[high]=temp;

    a is the array being searched or sorted. high is the right end of the current range. temp holds one value while two are swapped.

  15. return i+1;

    This line returns from the function. return exits the function and hands back a value.

  16. void quickSort(int a[],int low,int high) {

    This line defines a function. quickSort() partitions, then sorts both sides recursively. low is the left end of the current search or sort range.

  17. if(low<high) {

    This line is a decision. if runs the block only when the condition is true. low is the left end of the current search or sort range.

  18. int p=partition(a,low,high);

    partition() puts smaller elements left of the pivot and larger ones right. low is the left end of the current search or sort range. high is the right end of the current range.

  19. quickSort(a,low,p-1);

    quickSort() partitions, then sorts both sides recursively. low is the left end of the current search or sort range.

  20. quickSort(a,p+1,high);

    quickSort() partitions, then sorts both sides recursively. high is the right end of the current range.

  21. int main() {

    This line defines a function. main() is where the program starts running.

  22. int n,i;

    Declares the variables used below. n is the number of elements (or processes).

  23. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  24. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  25. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  26. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  29. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  30. quickSort(a,0,n-1);

    quickSort() partitions, then sorts both sides recursively. n is the number of elements (or processes).

  31. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  32. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  33. printf("\nAfter quick sorting:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  35. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  36. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  37. printf("\nTime complexity: O(n log n) average, O(n^2) worst");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  38. printf("\nSpace complexity: O(log n) average, O(n) worst");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  39. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  40. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Quick sort?

A. Best O(n log n), average O(n log n), worst O(n²). Design paradigm: Divide & conquer.

Q. Quick sort's worst case happens when…

A. The pivot is always the smallest or largest element. For example, a sorted array with the last element as pivot.

Q. partition() places the pivot…

A. At its final sorted position. Smaller elements go left of it and larger ones right.

Q. Is quick sort in-place?

A. Yes, it only needs the O(log n) recursion stack. Merge sort is the one needing O(n) extra space.

Program 09

Merge sort

Write a program in c to sort the elements using merge sort and find its execution time using the time function.

Run it

Algorithm

Algorithm: MergeSort(A, low, high)

1. Start
2. If (low < high) then
3.        mid <- (low+high)/2
4.        MergeSort(A, low, mid)
5.        MergeSort(A, mid+1, high)
6.        Merge(A, low, mid, high)
7. Stop

Algorithm: Merge(A, low, mid, high)

1. n1 <- mid-low+1, n2 <- high-mid
2. Copy A[low..mid] into L[0..n1-1] and A[mid+1..high] into R[0..n2-1]
3. i <- 0, j <- 0, k <- low
4. While (i < n1 and j < n2) do
5.        if L[i] <= R[j] then
6.              A[k] <- L[i], i <- i+1
7.        else
8.              A[k] <- R[j], j <- j+1
9.        k <- k+1
10. Copy the remaining elements of L and R into A
11. Return

Program

#include<stdio.h>
#include<time.h>

int count=0;

void merge(int a[],int low,int mid,int high) {
    int n1=mid-low+1,n2=high-mid;
    int left[n1],right[n2];
    int i,j,k;

    for(i=0;i<n1;i++)
        left[i]=a[low+i];
    for(j=0;j<n2;j++)
        right[j]=a[mid+1+j];

    i=0;
    j=0;
    k=low;
    while(i<n1 && j<n2) {
        count++;
        if(left[i]<=right[j])
            a[k++]=left[i++];
        else
            a[k++]=right[j++];
    }
    while(i<n1)
        a[k++]=left[i++];
    while(j<n2)
        a[k++]=right[j++];
}

void mergeSort(int a[],int low,int high) {
    if(low<high) {
        int mid=(low+high)/2;
        mergeSort(a,low,mid);
        mergeSort(a,mid+1,high);
        merge(a,low,mid,high);
    }
}

int main() {
    int n,i;
    printf("Enter the number of elements:");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements:");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    clock_t start=clock();
    mergeSort(a,0,n-1);
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nAfter merge sorting:");
    for(i=0;i<n;i++)
        printf("\t%d",a[i]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n log n)");
    printf("\nSpace complexity: O(n)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 42 8 27 14 35 19

Enter the number of elements:6
Enter the elements:42 8 27 14 35 19

After merge sorting:	8	14	19	27	35	42
Number of comparisons:11
Time taken:0.000008 seconds
Time complexity: O(n log n)
Space complexity: O(n)

Complexity

Time complexity: O(n log n)
Space complexity: O(n)
Best caseO(n log n)
Average caseO(n log n)
Worst caseO(n log n)
ParadigmDivide & conquer

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int count=0;

    Declares the variables used below. count tallies the basic operations (comparisons/steps) to show the complexity.

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

    This line defines a function. merge() combines two sorted halves into one sorted run. low is the left end of the current search or sort range.

  3. int n1=mid-low+1,n2=high-mid;

    Declares the variables used below. mid = (low + high) / 2 splits the range in half. low is the left end of the current search or sort range.

  4. int left[n1],right[n2];

    Declares the variables used below. left is the start index of the left half (or the left child). right is the end index of the right half (or the right child).

  5. int i,j,k;

    Declares the variables used below.

  6. for(i=0;i<n1;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  7. left[i]=a[low+i];

    left is the start index of the left half (or the left child). low is the left end of the current search or sort range.

  8. for(j=0;j<n2;j++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  9. right[j]=a[mid+1+j];

    right is the end index of the right half (or the right child). mid = (low + high) / 2 splits the range in half.

  10. i=0;

    i is the loop counter.

  11. j=0;

    j is the inner loop counter.

  12. k=low;

    low is the left end of the current search or sort range.

  13. while(i<n1 && j<n2) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  14. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  15. if(left[i]<=right[j])

    This line is a decision. if runs the block only when the condition is true. left is the start index of the left half (or the left child).

  16. a[k++]=left[i++];

    a is the array being searched or sorted. left is the start index of the left half (or the left child).

  17. a[k++]=right[j++];

    a is the array being searched or sorted. right is the end index of the right half (or the right child).

  18. while(i<n1)

    This line is a while loop. while (condition) repeats as long as the condition is true.

  19. while(j<n2)

    This line is a while loop. while (condition) repeats as long as the condition is true.

  20. void mergeSort(int a[],int low,int high) {

    This line defines a function. mergeSort() splits the array in half, sorts each half recursively, then merges. low is the left end of the current search or sort range.

  21. if(low<high) {

    This line is a decision. if runs the block only when the condition is true. low is the left end of the current search or sort range.

  22. int mid=(low+high)/2;

    mid = (low + high) / 2 splits the range in half. low is the left end of the current search or sort range. high is the right end of the current range.

  23. mergeSort(a,low,mid);

    mergeSort() splits the array in half, sorts each half recursively, then merges. low is the left end of the current search or sort range. mid = (low + high) / 2 splits the range in half.

  24. mergeSort(a,mid+1,high);

    mergeSort() splits the array in half, sorts each half recursively, then merges. mid = (low + high) / 2 splits the range in half. high is the right end of the current range.

  25. merge(a,low,mid,high);

    merge() combines two sorted halves into one sorted run. low is the left end of the current search or sort range. mid = (low + high) / 2 splits the range in half.

  26. int main() {

    This line defines a function. main() is where the program starts running.

  27. int n,i;

    Declares the variables used below. n is the number of elements (or processes).

  28. printf("Enter the number of elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  29. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  30. int a[n];

    Declares the variables used below. n is the number of elements (or processes).

  31. printf("Enter the elements:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  34. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  35. mergeSort(a,0,n-1);

    mergeSort() splits the array in half, sorts each half recursively, then merges. n is the number of elements (or processes).

  36. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  37. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  38. printf("\nAfter merge sorting:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  40. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  41. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  42. printf("\nTime complexity: O(n log n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  43. printf("\nSpace complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  44. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  45. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Merge sort?

A. Best O(n log n), average O(n log n), worst O(n log n). Design paradigm: Divide & conquer.

Q. Merge sort's recurrence is…

A. T(n) = 2T(n/2) + O(n). By the master theorem, that solves to O(n log n).

Q. Merge sort's extra space is…

A. O(n) for the temporary array. merge() copies both halves into a temporary array of size n before writing them back. Time stays O(n log n) in every case.

Dynamic programming

Program 10

Fibonacci (recursive)

Write a program in c to find the fibonacci series using recursion and find its execution time using the time function.

Run it

Algorithm

Algorithm: Fib(n)

1. Start
2. If (n <= 1) then
3.        Return n
4. Return Fib(n-1) + Fib(n-2)
5. Stop

Algorithm: FibonacciSeries(n)

1. Start
2. For i <- 0 to (n-1) do
3.        print Fib(i)
4. Stop

Program

#include<stdio.h>
#include<time.h>

int calls=0;

int fib(int n) {
    calls++;
    if(n<=1)
        return n;
    return fib(n-1)+fib(n-2);
}

int main() {
    int n,i;
    printf("Enter the number of terms:");
    scanf("%d",&n);

    clock_t start=clock();
    printf("\nFibonacci series:");
    for(i=0;i<n;i++)
        printf("\t%d",fib(i));
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nNumber of function calls:%d",calls);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(2^n)");
    printf("\nSpace complexity: O(n)");
    printf("\n");
    return 0;
}

Output

Input typed: 10

Enter the number of terms:10

Fibonacci series:	0	1	1	2	3	5	8	13	21	34
Number of function calls:276
Time taken:0.000009 seconds
Time complexity: O(2^n)
Space complexity: O(n)

Complexity

Time complexity: O(2^n)
Space complexity: O(n)
Best caseO(2ⁿ)
Average caseO(2ⁿ)
Worst caseO(2ⁿ)
ParadigmRecursion

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int calls=0;

    Declares the variables used below. calls counts the recursive calls, which shows the exponential blow-up.

  2. int fib(int n) {

    This line defines a function. fib() computes Fibonacci numbers, showing recursion vs dynamic programming. n is the number of elements (or processes).

  3. calls++;

    Counts one more basic operation. calls counts the recursive calls, which shows the exponential blow-up.

  4. if(n<=1)

    This line is a decision. if runs the block only when the condition is true. n is the number of elements (or processes).

  5. return n;

    This line returns from the function. return exits the function and hands back a value. n is the number of elements (or processes).

  6. return fib(n-1)+fib(n-2);

    This line returns from the function. return exits the function and hands back a value. fib() computes Fibonacci numbers, showing recursion vs dynamic programming.

  7. int main() {

    This line defines a function. main() is where the program starts running.

  8. int n,i;

    Declares the variables used below. n is the number of elements (or processes).

  9. printf("Enter the number of terms:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  10. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  11. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  12. printf("\nFibonacci series:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  14. printf("\t%d",fib(i));

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). fib() computes Fibonacci numbers, showing recursion vs dynamic programming.

  15. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  16. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  17. printf("\nNumber of function calls:%d",calls);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). calls counts the recursive calls, which shows the exponential blow-up.

  18. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  19. printf("\nTime complexity: O(2^n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  20. printf("\nSpace complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  21. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  22. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Fibonacci (recursive)?

A. Best O(2ⁿ), average O(2ⁿ), worst O(2ⁿ). Design paradigm: Recursion.

Q. Why is recursive Fibonacci exponential?

A. It recomputes the same subproblems many times. fib(n − 2) is computed by both fib(n) and fib(n − 1).

Program 11

Fibonacci (DP)

Write a program in c to find the fibonacci series using dynamic programming and find its execution time using the time function.

Run it

Algorithm

Algorithm: FibonacciDP(n)

1. Start
2. For i <- 0 to (n-1) do
3.        if (i <= 1) then
4.              F[i] <- i
5.        else
6.              F[i] <- F[i-1] + F[i-2]
7. Print F[0..n-1]
8. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,count=0;
    printf("Enter the number of terms:");
    scanf("%d",&n);
    int f[n];

    clock_t start=clock();
    for(i=0;i<n;i++) {
        count++;
        if(i<=1)
            f[i]=i;
        else
            f[i]=f[i-1]+f[i-2];
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nFibonacci series:");
    for(i=0;i<n;i++)
        printf("\t%d",f[i]);
    printf("\nNumber of iterations:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n)");
    printf("\nSpace complexity: O(n)");
    printf("\n");
    return 0;
}

Output

Input typed: 10

Enter the number of terms:10

Fibonacci series:	0	1	1	2	3	5	8	13	21	34
Number of iterations:10
Time taken:0.000003 seconds
Time complexity: O(n)
Space complexity: O(n)

Complexity

Time complexity: O(n)
Space complexity: O(n)
Best caseO(n)
Average caseO(n)
Worst caseO(n)
ParadigmDynamic programming

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  3. printf("Enter the number of terms:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int f[n];

    Declares the variables used below. n is the number of elements (or processes).

  6. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  7. for(i=0;i<n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  8. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  9. if(i<=1)

    This line is a decision. if runs the block only when the condition is true.

  10. f[i]=i;

    i is the loop counter.

  11. f[i]=f[i-1]+f[i-2];

    i is the loop counter.

  12. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  13. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  14. printf("\nFibonacci series:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  16. printf("\t%d",f[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  17. printf("\nNumber of iterations:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  18. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  19. printf("\nTime complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  20. printf("\nSpace complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  21. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  22. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Fibonacci (DP)?

A. Best O(n), average O(n), worst O(n). Design paradigm: Dynamic programming.

Q. The two key properties DP needs are…

A. Overlapping subproblems and optimal substructure. Fibonacci has overlapping subproblems, so storing them gives O(n).

Q. Memoization vs tabulation:

A. Top-down with a cache vs bottom-up filling a table. This program fills f[0..n] bottom-up (tabulation).

Program 12

Matrix chain multiplication

Write a program in c to find the minimum number of scalar multiplications needed for matrix chain multiplication using dynamic programming and find its execution time using the time function.

Run it

Algorithm

Algorithm: MatrixChainOrder(p, n)

1. Start
2. For i <- 1 to n do
3.        m[i][i] <- 0
4. For l <- 2 to n do
5.        For i <- 1 to (n-l+1) do
6.              j <- i+l-1
7.              m[i][j] <- infinity
8.              For k <- i to (j-1) do
9.                    q <- m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
10.                   if q < m[i][j] then
11.                         m[i][j] <- q
12.                         s[i][j] <- k
13. Print m[1][n] and PrintOrder(s, 1, n)
14. Stop

Algorithm: PrintOrder(s, i, j)

1. If (i == j) then
2.        print "A"i
3. else
4.        print "("
5.        PrintOrder(s, i, s[i][j])
6.        PrintOrder(s, s[i][j]+1, j)
7.        print ")"

Program

#include<stdio.h>
#include<time.h>

int s[20][20];

void printOrder(int i,int j) {
    if(i==j) {
        printf("A%d",i);
        return;
    }
    printf("(");
    printOrder(i,s[i][j]);
    printOrder(s[i][j]+1,j);
    printf(")");
}

int main() {
    int n,i,j,k,l,count=0;
    printf("Enter the number of matrices:");
    scanf("%d",&n);
    int p[n+1];
    printf("Enter the %d dimensions (matrix i is p[i-1] x p[i]):",n+1);
    for(i=0;i<=n;i++)
        scanf("%d",&p[i]);
    int m[20][20];

    clock_t start=clock();
    for(i=1;i<=n;i++)
        m[i][i]=0;
    for(l=2;l<=n;l++) {
        for(i=1;i<=n-l+1;i++) {
            j=i+l-1;
            m[i][j]=999999999;
            for(k=i;k<j;k++) {
                count++;
                int cost=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
                if(cost<m[i][j]) {
                    m[i][j]=cost;
                    s[i][j]=k;
                }
            }
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nCost table:");
    for(i=1;i<=n;i++) {
        printf("\n");
        for(j=1;j<=n;j++)
            if(j<i)
                printf("\t-");
            else
                printf("\t%d",m[i][j]);
    }
    printf("\nMinimum number of multiplications:%d",m[1][n]);
    printf("\nOptimal parenthesization:");
    printOrder(1,n);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n^3)");
    printf("\nSpace complexity: O(n^2)");
    printf("\n");
    return 0;
}

Output

Input typed: 4 ⏎ 5 4 6 2 7

Enter the number of matrices:4
Enter the 5 dimensions (matrix i is p[i-1] x p[i]):5 4 6 2 7

Cost table:
	0	120	88	158
	-	0	48	104
	-	-	0	84
	-	-	-	0
Minimum number of multiplications:158
Optimal parenthesization:((A1(A2A3))A4)
Number of comparisons:10
Time taken:0.000004 seconds
Time complexity: O(n^3)
Space complexity: O(n^2)

Complexity

Time complexity: O(n^3)
Space complexity: O(n^2)
Best caseO(n³)
Average caseO(n³)
Worst caseO(n³)
ParadigmDynamic programming

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int s[20][20];

    Declares the variables used below.

  2. void printOrder(int i,int j) {

    This line defines a function. printOrder() prints the optimal parenthesisation recursively.

  3. if(i==j) {

    This line is a decision. if runs the block only when the condition is true.

  4. printf("A%d",i);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  5. return;

    This line returns from the function. return exits the function and hands back a value.

  6. printf("(");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  7. printOrder(i,s[i][j]);

    printOrder() prints the optimal parenthesisation recursively.

  8. printOrder(s[i][j]+1,j);

    printOrder() prints the optimal parenthesisation recursively.

  9. printf(")");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  10. int main() {

    This line defines a function. main() is where the program starts running.

  11. int n,i,j,k,l,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  12. printf("Enter the number of matrices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  13. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  14. int p[n+1];

    Declares the variables used below. n is the number of elements (or processes).

  15. printf("Enter the %d dimensions (matrix i is p[i-1] x p[i]):",n+1);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  18. int m[20][20];

    Declares the variables used below.

  19. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  21. m[i][i]=0;

    i is the loop counter.

  22. for(l=2;l<=n;l++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  23. for(i=1;i<=n-l+1;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  24. j=i+l-1;

    j is the inner loop counter.

  25. m[i][j]=999999999;

    i is the loop counter.

  26. for(k=i;k<j;k++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  27. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  28. int cost=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];

    Declares the variables used below. cost holds the edge weights (the adjacency/cost matrix).

  29. if(cost<m[i][j]) {

    This line is a decision. if runs the block only when the condition is true. cost holds the edge weights (the adjacency/cost matrix).

  30. m[i][j]=cost;

    i is the loop counter. cost holds the edge weights (the adjacency/cost matrix).

  31. s[i][j]=k;

    i is the loop counter.

  32. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  33. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  34. printf("\nCost table:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  35. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  36. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  38. if(j<i)

    This line is a decision. if runs the block only when the condition is true.

  39. printf("\t-");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  40. printf("\t%d",m[i][j]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  41. printf("\nMinimum number of multiplications:%d",m[1][n]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  42. printf("\nOptimal parenthesization:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  43. printOrder(1,n);

    printOrder() prints the optimal parenthesisation recursively. n is the number of elements (or processes).

  44. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  45. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  46. printf("\nTime complexity: O(n^3)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  47. printf("\nSpace complexity: O(n^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  48. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Matrix chain multiplication?

A. Best O(n³), average O(n³), worst O(n³). Design paradigm: Dynamic programming.

Q. Matrix chain multiplication decides…

A. The parenthesisation with the fewest scalar multiplications. The product is the same either way; only the cost changes.

Q. Cost of multiplying a p×q by a q×r matrix:

A. p × q × r. m[i][j] = min over k of m[i][k] + m[k+1][j] + p(i−1)·p(k)·p(j).

Program 13

0/1 knapsack

Write a program in c to solve the 0/1 knapsack problem using dynamic programming and find its execution time using the time function.

Run it

Algorithm

Algorithm: Knapsack01(v, wt, n, W)

1. Start
2. For w <- 0 to W do
3.        V[0][w] <- 0
4. For i <- 1 to n do
5.        For w <- 0 to W do
6.              if wt[i] <= w and v[i] + V[i-1][w-wt[i]] > V[i-1][w] then
7.                    V[i][w] <- v[i] + V[i-1][w-wt[i]]
8.                    keep[i][w] <- 1
9.              else
10.                   V[i][w] <- V[i-1][w]
11.                   keep[i][w] <- 0
12. print "Maximum value" V[n][W]
13. w <- W
14. For i <- n down to 1 do
15.       if keep[i][w] == 1 then
16.             print "Item i selected"
17.             w <- w - wt[i]
18. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,W,i,w,count=0;
    printf("Enter the number of items:");
    scanf("%d",&n);
    int v[n+1],wt[n+1];
    printf("Enter the values of %d items:",n);
    for(i=1;i<=n;i++)
        scanf("%d",&v[i]);
    printf("Enter the weights of %d items:",n);
    for(i=1;i<=n;i++)
        scanf("%d",&wt[i]);
    printf("Enter the capacity of the knapsack:");
    scanf("%d",&W);
    int V[n+1][W+1],keep[n+1][W+1];

    clock_t start=clock();
    for(w=0;w<=W;w++)
        V[0][w]=0;
    for(i=1;i<=n;i++) {
        for(w=0;w<=W;w++) {
            count++;
            if(wt[i]<=w && v[i]+V[i-1][w-wt[i]]>V[i-1][w]) {
                V[i][w]=v[i]+V[i-1][w-wt[i]];
                keep[i][w]=1;
            }
            else {
                V[i][w]=V[i-1][w];
                keep[i][w]=0;
            }
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nV[i,w] table:\ni\\w");
    for(w=0;w<=W;w++)
        printf("\t%d",w);
    for(i=0;i<=n;i++) {
        printf("\n%d",i);
        for(w=0;w<=W;w++)
            printf("\t%d",V[i][w]);
    }
    printf("\nMaximum value:%d",V[n][W]);
    printf("\nItems selected:");
    w=W;
    for(i=n;i>=1;i--) {
        if(keep[i][w]==1) {
            printf("\tItem %d(v=%d,w=%d)",i,v[i],wt[i]);
            w=w-wt[i];
        }
    }
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(nW)");
    printf("\nSpace complexity: O(nW)");
    printf("\n");
    return 0;
}

Output

Input typed: 4 ⏎ 10 40 30 50 ⏎ 5 4 6 3 ⏎ 10

Enter the number of items:4
Enter the values of 4 items:10 40 30 50
Enter the weights of 4 items:5 4 6 3
Enter the capacity of the knapsack:10

V[i,w] table:
i\w	0	1	2	3	4	5	6	7	8	9	10
0	0	0	0	0	0	0	0	0	0	0	0
1	0	0	0	0	0	10	10	10	10	10	10
2	0	0	0	0	40	40	40	40	40	50	50
3	0	0	0	0	40	40	40	40	40	50	70
4	0	0	0	50	50	50	50	90	90	90	90
Maximum value:90
Items selected:	Item 4(v=50,w=3)	Item 2(v=40,w=4)
Number of comparisons:44
Time taken:0.000001 seconds
Time complexity: O(nW)
Space complexity: O(nW)

Complexity

Time complexity: O(nW)
Space complexity: O(nW)
Best caseO(nW)
Average caseO(nW)
Worst caseO(nW)
ParadigmDynamic programming

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,W,i,w,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  3. printf("Enter the number of items:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int v[n+1],wt[n+1];

    Declares the variables used below. n is the number of elements (or processes). wt holds each process's waiting time.

  6. printf("Enter the values of %d items:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  8. scanf("%d",&v[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  9. printf("Enter the weights of %d items:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  10. scanf("%d",&wt[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &. wt holds each process's waiting time.

  11. printf("Enter the capacity of the knapsack:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  12. scanf("%d",&W);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  13. int V[n+1][W+1],keep[n+1][W+1];

    Declares the variables used below. n is the number of elements (or processes). keep marks what is kept in the current solution.

  14. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  15. for(w=0;w<=W;w++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  16. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  17. for(w=0;w<=W;w++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  18. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  19. if(wt[i]<=w && v[i]+V[i-1][w-wt[i]]>V[i-1][w]) {

    This line is a decision. if runs the block only when the condition is true. wt holds each process's waiting time.

  20. V[i][w]=v[i]+V[i-1][w-wt[i]];

    i is the loop counter. wt holds each process's waiting time.

  21. keep[i][w]=1;

    keep marks what is kept in the current solution.

  22. else {

    This line is a decision. else runs when the if condition was false.

  23. V[i][w]=V[i-1][w];

    i is the loop counter.

  24. keep[i][w]=0;

    keep marks what is kept in the current solution.

  25. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  26. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  27. printf("\nV[i,w] table:\ni\\w");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  28. printf("\t%d",w);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  29. for(i=0;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  30. printf("\n%d",i);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  31. printf("\t%d",V[i][w]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  32. printf("\nMaximum value:%d",V[n][W]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  33. printf("\nItems selected:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  34. for(i=n;i>=1;i--) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  35. if(keep[i][w]==1) {

    This line is a decision. if runs the block only when the condition is true. keep marks what is kept in the current solution.

  36. printf("\tItem %d(v=%d,w=%d)",i,v[i],wt[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). wt holds each process's waiting time.

  37. w=w-wt[i];

    wt holds each process's waiting time.

  38. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  39. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  40. printf("\nTime complexity: O(nW)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  41. printf("\nSpace complexity: O(nW)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  42. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  43. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of 0/1 knapsack?

A. Best O(nW), average O(nW), worst O(nW). Design paradigm: Dynamic programming.

Q. In 0/1 knapsack, each item is…

A. Taken whole or left out. Fractions are allowed only in the fractional (greedy) version.

Q. The DP table K[i][w] stores…

A. The best value using the first i items with capacity w. K[i][w] = max(K[i−1][w], v[i] + K[i−1][w − wt[i]]).

Q. Why is O(nW) called pseudo-polynomial?

A. It grows with the numeric value W, not with the input size. Doubling W's digits makes W exponentially larger.

Program 14

Longest common subsequence

Write a program in c to find the longest common subsequence (LCS) of two sequences using dynamic programming and find its execution time using the time function.

Run it

Algorithm

Algorithm: LCS-Length(X, Y, m, n)

1. Start
2. For i <- 1 to m do
3.        c[i][0] <- 0
4. For j <- 0 to n do
5.        c[0][j] <- 0
6. For i <- 1 to m do
7.        For j <- 1 to n do
8.              if X[i] == Y[j] then
9.                    c[i][j] <- c[i-1][j-1] + 1
10.                   b[i][j] <- 'D'
11.             else if c[i-1][j] >= c[i][j-1] then
12.                   c[i][j] <- c[i-1][j]
13.                   b[i][j] <- 'U'
14.             else
15.                   c[i][j] <- c[i][j-1]
16.                   b[i][j] <- 'L'
17. print "Length of LCS" c[m][n]
18. PrintLCS(b, X, m, n)
19. Stop

Algorithm: PrintLCS(b, X, i, j)

1. If (i == 0 or j == 0) then
2.        Return
3. If b[i][j] == 'D' then
4.        PrintLCS(b, X, i-1, j-1)
5.        print X[i]
6. else if b[i][j] == 'U' then
7.        PrintLCS(b, X, i-1, j)
8. else
9.        PrintLCS(b, X, i, j-1)

Program

#include<stdio.h>
#include<string.h>
#include<time.h>

int c[50][50];
char b[50][50];
char x[50],y[50];

void printLCS(int i,int j) {
    if(i==0 || j==0)
        return;
    if(b[i][j]=='D') {
        printLCS(i-1,j-1);
        printf("%c",x[i-1]);
    }
    else if(b[i][j]=='U')
        printLCS(i-1,j);
    else
        printLCS(i,j-1);
}

int main() {
    int m,n,i,j,count=0;
    printf("Enter the first sequence X:");
    scanf("%s",x);
    printf("Enter the second sequence Y:");
    scanf("%s",y);
    m=strlen(x);
    n=strlen(y);

    clock_t start=clock();
    for(i=1;i<=m;i++)
        c[i][0]=0;
    for(j=0;j<=n;j++)
        c[0][j]=0;
    for(i=1;i<=m;i++) {
        for(j=1;j<=n;j++) {
            count++;
            if(x[i-1]==y[j-1]) {
                c[i][j]=c[i-1][j-1]+1;
                b[i][j]='D';
            }
            else if(c[i-1][j]>=c[i][j-1]) {
                c[i][j]=c[i-1][j];
                b[i][j]='U';
            }
            else {
                c[i][j]=c[i][j-1];
                b[i][j]='L';
            }
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nc[i,j] table (D=diagonal, U=up, L=left):\n\t\t");
    for(j=0;j<n;j++)
        printf("%c\t",y[j]);
    for(i=0;i<=m;i++) {
        printf("\n");
        if(i==0)
            printf("\t");
        else
            printf("%c\t",x[i-1]);
        for(j=0;j<=n;j++)
            if(i==0 || j==0)
                printf("%d\t",c[i][j]);
            else
                printf("%d%c\t",c[i][j],b[i][j]);
    }
    printf("\nLength of LCS:%d",c[m][n]);
    printf("\nLCS:");
    printLCS(m,n);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(mn)");
    printf("\nSpace complexity: O(mn)");
    printf("\n");
    return 0;
}

Output

Input typed: ABCBDAB ⏎ BDCABA

Enter the first sequence X:ABCBDAB
Enter the second sequence Y:BDCABA

c[i,j] table (D=diagonal, U=up, L=left):
		B	D	C	A	B	A
	0	0	0	0	0	0	0
A	0	0U	0U	0U	1D	1L	1D
B	0	1D	1L	1L	1U	2D	2L
C	0	1U	1U	2D	2L	2U	2U
B	0	1D	1U	2U	2U	3D	3L
D	0	1U	2D	2U	2U	3U	3U
A	0	1U	2U	2U	3D	3U	4D
B	0	1D	2U	2U	3U	4D	4U
Length of LCS:4
LCS:BCBA
Number of comparisons:42
Time taken:0.000002 seconds
Time complexity: O(mn)
Space complexity: O(mn)

Complexity

Time complexity: O(mn)
Space complexity: O(mn)
Best caseO(mn)
Average caseO(mn)
Worst caseO(mn)
ParadigmDynamic programming

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <string.h>?

A. string.h: strlen, strcpy, strcmp, memset. Used here for: strlen.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int c[50][50];

    Declares the variables used below.

  2. char b[50][50];

    Declares the variables used below.

  3. char x[50],y[50];

    Declares the variables used below.

  4. void printLCS(int i,int j) {

    This line defines a function. printLCS() walks the table backwards to print the common subsequence.

  5. if(i==0 || j==0)

    This line is a decision. if runs the block only when the condition is true.

  6. return;

    This line returns from the function. return exits the function and hands back a value.

  7. if(b[i][j]=='D') {

    This line is a decision. if runs the block only when the condition is true.

  8. printLCS(i-1,j-1);

    printLCS() walks the table backwards to print the common subsequence.

  9. printf("%c",x[i-1]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  10. else if(b[i][j]=='U')

    This line is a decision. else runs when the if condition was false. if runs the block only when the condition is true.

  11. printLCS(i-1,j);

    printLCS() walks the table backwards to print the common subsequence.

  12. printLCS(i,j-1);

    printLCS() walks the table backwards to print the common subsequence.

  13. int main() {

    This line defines a function. main() is where the program starts running.

  14. int m,n,i,j,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  15. printf("Enter the first sequence X:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  16. scanf("%s",x);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  17. printf("Enter the second sequence Y:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  18. scanf("%s",y);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  19. m=strlen(x);

    strlen() returns the length of a string (without the '\0').

  20. n=strlen(y);

    n is the number of elements (or processes). strlen() returns the length of a string (without the '\0').

  21. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  22. for(i=1;i<=m;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  23. c[i][0]=0;

    i is the loop counter.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  25. c[0][j]=0;

    j is the inner loop counter.

  26. for(i=1;i<=m;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  27. for(j=1;j<=n;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  28. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  29. if(x[i-1]==y[j-1]) {

    This line is a decision. if runs the block only when the condition is true.

  30. c[i][j]=c[i-1][j-1]+1;

    i is the loop counter.

  31. b[i][j]='D';

    i is the loop counter.

  32. else if(c[i-1][j]>=c[i][j-1]) {

    This line is a decision. else runs when the if condition was false. if runs the block only when the condition is true.

  33. c[i][j]=c[i-1][j];

    i is the loop counter.

  34. b[i][j]='U';

    i is the loop counter.

  35. else {

    This line is a decision. else runs when the if condition was false.

  36. c[i][j]=c[i][j-1];

    i is the loop counter.

  37. b[i][j]='L';

    i is the loop counter.

  38. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  39. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  40. printf("\nc[i,j] table (D=diagonal, U=up, L=left):\n\t\t");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  42. printf("%c\t",y[j]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  43. for(i=0;i<=m;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  44. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  45. if(i==0)

    This line is a decision. if runs the block only when the condition is true.

  46. printf("\t");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  47. printf("%c\t",x[i-1]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  48. printf("%d\t",c[i][j]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  49. printf("%d%c\t",c[i][j],b[i][j]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  50. printf("\nLength of LCS:%d",c[m][n]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  51. printf("\nLCS:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  52. printLCS(m,n);

    printLCS() walks the table backwards to print the common subsequence. n is the number of elements (or processes).

  53. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  54. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  55. printf("\nTime complexity: O(mn)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  56. printf("\nSpace complexity: O(mn)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  57. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Longest common subsequence?

A. Best O(mn), average O(mn), worst O(mn). Design paradigm: Dynamic programming.

Q. Subsequence vs substring:

A. A subsequence keeps the order but can skip characters. BCBA is an LCS of ABCBDAB and BDCABA (length 4).

Q. When x[i] = y[j], c[i][j] =

A. c[i−1][j−1] + 1. Otherwise take the max of the cells above and to the left.

Program 19

Travelling salesman (DP)

Write a program in c to solve the travelling salesman problem using dynamic programming and find its execution time using the time function.

Run it

Algorithm

Algorithm: TSP(cost, n)
(g(i, S) = cheapest path that starts at city i, visits every city in set S once, and ends at city 1)

1. Start
2. For i <- 2 to n do
3.        g(i, {}) <- cost[i][1]
4. For each set S not containing city 1, in increasing size do
5.        For each city i not in S do
6.              g(i, S) <- infinity
7.              For each city k in S do
8.                    if cost[i][k] + g(k, S - {k}) < g(i, S) then
9.                          g(i, S) <- cost[i][k] + g(k, S - {k})
10.                         next(i, S) <- k
11. print "Minimum cost" g(1, {2, 3, ..., n})
12. Follow next(i, S) from city 1 to print the tour
13. Stop

Program

#include<stdio.h>
#include<time.h>

int cost[15][15];
int g[1<<15][15],nxt[1<<15][15];

int main() {
    int n,i,j,k,S,full,count=0;
    printf("Enter the number of cities:");
    scanf("%d",&n);
    printf("Enter the %dx%d cost matrix:\n",n,n);
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            scanf("%d",&cost[i][j]);

    clock_t start=clock();
    // S is a bitmask of cities; bit 0 (city 1) is never in S
    full=(1<<n)-1;
    for(i=0;i<n;i++)
        g[0][i]=cost[i][0];
    for(S=1;S<=full;S++) {
        if(S&1)
            continue;
        for(i=0;i<n;i++) {
            if(S&(1<<i))
                continue;
            g[S][i]=999999999;
            for(k=1;k<n;k++) {
                if(S&(1<<k)) {
                    count++;
                    int c=cost[i][k]+g[S^(1<<k)][k];
                    if(c<g[S][i]) {
                        g[S][i]=c;
                        nxt[S][i]=k;
                    }
                }
            }
        }
    }
    S=full^1;
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nMinimum cost of tour:%d",g[S][0]);
    printf("\nOptimal tour:1");
    i=0;
    while(S!=0) {
        k=nxt[S][i];
        printf(" -> %d",k+1);
        S=S^(1<<k);
        i=k;
    }
    printf(" -> 1");
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n^2 * 2^n)");
    printf("\nSpace complexity: O(n * 2^n)");
    printf("\n");
    return 0;
}

Output

Input typed: 4 ⏎ 0 10 15 20 ⏎ 5 0 9 10 ⏎ 6 13 0 12 ⏎ 8 8 9 0

Enter the number of cities:4
Enter the 4x4 cost matrix:
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0

Minimum cost of tour:35
Optimal tour:1 -> 2 -> 4 -> 3 -> 1
Number of comparisons:24
Time taken:0.000008 seconds
Time complexity: O(n^2 * 2^n)
Space complexity: O(n * 2^n)

Complexity

Time complexity: O(n^2 * 2^n)
Space complexity: O(n * 2^n)
Best caseO(n²·2ⁿ)
Average caseO(n²·2ⁿ)
Worst caseO(n²·2ⁿ)
ParadigmDynamic programming

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int cost[15][15];

    Declares the variables used below. cost holds the edge weights (the adjacency/cost matrix).

  2. int g[1<<15][15],nxt[1<<15][15];

    Declares the variables used below. nxt is the next node to visit.

  3. int main() {

    This line defines a function. main() is where the program starts running.

  4. int n,i,j,k,S,full,count=0;

    Declares the variables used below. n is the number of elements (or processes). full checks whether the container is at capacity.

  5. printf("Enter the number of cities:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  6. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  7. printf("Enter the %dx%d cost matrix:\n",n,n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &. cost holds the edge weights (the adjacency/cost matrix).

  11. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  12. full=(1<<n)-1;

    full checks whether the container is at capacity. n is the number of elements (or processes).

  13. g[0][i]=cost[i][0];

    i is the loop counter. cost holds the edge weights (the adjacency/cost matrix).

  14. for(S=1;S<=full;S++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. full checks whether the container is at capacity.

  15. if(S&1)

    This line is a decision. if runs the block only when the condition is true.

  16. continue;

    continue skips to the next loop iteration.

  17. for(i=0;i<n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  18. if(S&(1<<i))

    This line is a decision. if runs the block only when the condition is true.

  19. g[S][i]=999999999;

    i is the loop counter.

  20. for(k=1;k<n;k++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  21. if(S&(1<<k)) {

    This line is a decision. if runs the block only when the condition is true.

  22. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  23. int c=cost[i][k]+g[S^(1<<k)][k];

    cost holds the edge weights (the adjacency/cost matrix).

  24. if(c<g[S][i]) {

    This line is a decision. if runs the block only when the condition is true.

  25. g[S][i]=c;

    i is the loop counter.

  26. nxt[S][i]=k;

    nxt is the next node to visit.

  27. S=full^1;

    full checks whether the container is at capacity.

  28. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  29. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  30. printf("\nMinimum cost of tour:%d",g[S][0]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  31. printf("\nOptimal tour:1");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  32. i=0;

    i is the loop counter.

  33. while(S!=0) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  34. k=nxt[S][i];

    nxt is the next node to visit.

  35. printf(" -> %d",k+1);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  36. i=k;

    i is the loop counter.

  37. printf(" -> 1");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  38. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  39. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  40. printf("\nTime complexity: O(n^2 * 2^n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  41. printf("\nSpace complexity: O(n * 2^n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  42. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  43. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Travelling salesman (DP)?

A. Best O(n²·2ⁿ), average O(n²·2ⁿ), worst O(n²·2ⁿ). Design paradigm: Dynamic programming.

Q. The Held–Karp DP state g(i, S) is…

A. The shortest path from i through every city in S, back to the start. That's 2ⁿ subsets × n cities.

Q. TSP is…

A. NP-hard. DP is exact but exponential, and brute force is O(n!).

Greedy

Program 15

Fractional knapsack

Write a program in c to solve the fractional knapsack problem using the greedy method and find its execution time using the time function.

Run it

Algorithm

Algorithm: FractionalKnapsack(v, w, n, W)

1. Start
2. For i <- 1 to n do
3.        r[i] <- v[i]/w[i]
4.        x[i] <- 0
5. Sort the items in decreasing order of r[i] (merge sort)
6. remaining <- W, total <- 0
7. For each item i in sorted order, while remaining > 0 do
8.        if w[i] <= remaining then
9.              x[i] <- 1
10.             remaining <- remaining - w[i]
11.       else
12.             x[i] <- remaining/w[i]
13.             remaining <- 0
14.       total <- total + x[i]*v[i]
15. print "Maximum value" total
16. Stop

Program

#include<stdio.h>
#include<time.h>

double r[50];
int count=0;

void merge(int a[],int low,int mid,int high) {
    int n1=mid-low+1,n2=high-mid;
    int left[n1],right[n2];
    int i,j,k;

    for(i=0;i<n1;i++)
        left[i]=a[low+i];
    for(j=0;j<n2;j++)
        right[j]=a[mid+1+j];

    i=0;
    j=0;
    k=low;
    while(i<n1 && j<n2) {
        count++;
        if(r[left[i]]>=r[right[j]])
            a[k++]=left[i++];
        else
            a[k++]=right[j++];
    }
    while(i<n1)
        a[k++]=left[i++];
    while(j<n2)
        a[k++]=right[j++];
}

void mergeSort(int a[],int low,int high) {
    if(low<high) {
        int mid=(low+high)/2;
        mergeSort(a,low,mid);
        mergeSort(a,mid+1,high);
        merge(a,low,mid,high);
    }
}

int main() {
    int n,i,k;
    double W;
    printf("Enter the number of items:");
    scanf("%d",&n);
    double v[n+1],w[n+1],x[n+1];
    int order[n];
    printf("Enter the values of %d items:",n);
    for(i=1;i<=n;i++)
        scanf("%lf",&v[i]);
    printf("Enter the weights of %d items:",n);
    for(i=1;i<=n;i++)
        scanf("%lf",&w[i]);
    printf("Enter the capacity of the knapsack:");
    scanf("%lf",&W);

    clock_t start=clock();
    for(i=1;i<=n;i++) {
        r[i]=v[i]/w[i];
        x[i]=0;
        order[i-1]=i;
    }
    mergeSort(order,0,n-1);
    double remaining=W,total=0;
    for(k=0;k<n && remaining>0;k++) {
        i=order[k];
        count++;
        if(w[i]<=remaining) {
            x[i]=1;
            remaining=remaining-w[i];
        }
        else {
            x[i]=remaining/w[i];
            remaining=0;
        }
        total=total+x[i]*v[i];
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nItems in decreasing order of value/weight:\nItem\tValue\tWeight\tv/w\tFraction");
    for(k=0;k<n;k++) {
        i=order[k];
        printf("\n%d\t%g\t%g\t%g\t%g",i,v[i],w[i],r[i],x[i]);
    }
    printf("\nMaximum value:%g",total);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n log n)");
    printf("\nSpace complexity: O(n)");
    printf("\n");
    return 0;
}

Output

Input typed: 4 ⏎ 10 40 30 50 ⏎ 5 4 6 3 ⏎ 10

Enter the number of items:4
Enter the values of 4 items:10 40 30 50
Enter the weights of 4 items:5 4 6 3
Enter the capacity of the knapsack:10

Items in decreasing order of value/weight:
Item	Value	Weight	v/w	Fraction
4	50	3	16.6667	1
2	40	4	10	1
3	30	6	5	0.5
1	10	5	2	0
Maximum value:105
Number of comparisons:8
Time taken:0.000006 seconds
Time complexity: O(n log n)
Space complexity: O(n)

Complexity

Time complexity: O(n log n)
Space complexity: O(n)
Best caseO(n log n)
Average caseO(n log n)
Worst caseO(n log n)
ParadigmGreedy

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. double r[50];

    Declares the variables used below.

  2. int count=0;

    Declares the variables used below. count tallies the basic operations (comparisons/steps) to show the complexity.

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

    This line defines a function. merge() combines two sorted halves into one sorted run. low is the left end of the current search or sort range.

  4. int n1=mid-low+1,n2=high-mid;

    Declares the variables used below. mid = (low + high) / 2 splits the range in half. low is the left end of the current search or sort range.

  5. int left[n1],right[n2];

    Declares the variables used below. left is the start index of the left half (or the left child). right is the end index of the right half (or the right child).

  6. int i,j,k;

    Declares the variables used below.

  7. for(i=0;i<n1;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  8. left[i]=a[low+i];

    left is the start index of the left half (or the left child). low is the left end of the current search or sort range.

  9. for(j=0;j<n2;j++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  10. right[j]=a[mid+1+j];

    right is the end index of the right half (or the right child). mid = (low + high) / 2 splits the range in half.

  11. i=0;

    i is the loop counter.

  12. j=0;

    j is the inner loop counter.

  13. k=low;

    low is the left end of the current search or sort range.

  14. while(i<n1 && j<n2) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  15. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  16. if(r[left[i]]>=r[right[j]])

    This line is a decision. if runs the block only when the condition is true. left is the start index of the left half (or the left child).

  17. a[k++]=left[i++];

    a is the array being searched or sorted. left is the start index of the left half (or the left child).

  18. a[k++]=right[j++];

    a is the array being searched or sorted. right is the end index of the right half (or the right child).

  19. while(i<n1)

    This line is a while loop. while (condition) repeats as long as the condition is true.

  20. while(j<n2)

    This line is a while loop. while (condition) repeats as long as the condition is true.

  21. void mergeSort(int a[],int low,int high) {

    This line defines a function. mergeSort() splits the array in half, sorts each half recursively, then merges. low is the left end of the current search or sort range.

  22. if(low<high) {

    This line is a decision. if runs the block only when the condition is true. low is the left end of the current search or sort range.

  23. int mid=(low+high)/2;

    mid = (low + high) / 2 splits the range in half. low is the left end of the current search or sort range. high is the right end of the current range.

  24. mergeSort(a,low,mid);

    mergeSort() splits the array in half, sorts each half recursively, then merges. low is the left end of the current search or sort range. mid = (low + high) / 2 splits the range in half.

  25. mergeSort(a,mid+1,high);

    mergeSort() splits the array in half, sorts each half recursively, then merges. mid = (low + high) / 2 splits the range in half. high is the right end of the current range.

  26. merge(a,low,mid,high);

    merge() combines two sorted halves into one sorted run. low is the left end of the current search or sort range. mid = (low + high) / 2 splits the range in half.

  27. int main() {

    This line defines a function. main() is where the program starts running.

  28. int n,i,k;

    Declares the variables used below. n is the number of elements (or processes).

  29. double W;

    Declares the variables used below.

  30. printf("Enter the number of items:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  31. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  32. double v[n+1],w[n+1],x[n+1];

    Declares the variables used below. n is the number of elements (or processes).

  33. int order[n];

    Declares the variables used below. order stores the sequence in which nodes are visited. n is the number of elements (or processes).

  34. printf("Enter the values of %d items:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  36. scanf("%lf",&v[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  37. printf("Enter the weights of %d items:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  38. scanf("%lf",&w[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  39. printf("Enter the capacity of the knapsack:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  40. scanf("%lf",&W);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  41. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  42. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  43. r[i]=v[i]/w[i];

    i is the loop counter.

  44. x[i]=0;

    i is the loop counter.

  45. order[i-1]=i;

    order stores the sequence in which nodes are visited.

  46. mergeSort(order,0,n-1);

    mergeSort() splits the array in half, sorts each half recursively, then merges. order stores the sequence in which nodes are visited. n is the number of elements (or processes).

  47. double remaining=W,total=0;

    Declares the variables used below. remaining is the burst time still left for each process. total accumulates the running sum (cost, value or weight).

  48. for(k=0;k<n && remaining>0;k++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  49. i=order[k];

    i is the loop counter. order stores the sequence in which nodes are visited.

  50. if(w[i]<=remaining) {

    This line is a decision. if runs the block only when the condition is true. remaining is the burst time still left for each process.

  51. x[i]=1;

    i is the loop counter.

  52. remaining=remaining-w[i];

    remaining is the burst time still left for each process.

  53. else {

    This line is a decision. else runs when the if condition was false.

  54. x[i]=remaining/w[i];

    i is the loop counter. remaining is the burst time still left for each process.

  55. remaining=0;

    remaining is the burst time still left for each process.

  56. total=total+x[i]*v[i];

    total accumulates the running sum (cost, value or weight).

  57. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  58. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  59. printf("\nItems in decreasing order of value/weight:\nItem\tValue\tWeight\tv/w\tFraction");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  60. for(k=0;k<n;k++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  61. printf("\n%d\t%g\t%g\t%g\t%g",i,v[i],w[i],r[i],x[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  62. printf("\nMaximum value:%g",total);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). total accumulates the running sum (cost, value or weight).

  63. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  64. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  65. printf("\nTime complexity: O(n log n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  66. printf("\nSpace complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  67. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  68. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Fractional knapsack?

A. Best O(n log n), average O(n log n), worst O(n log n). Design paradigm: Greedy.

Q. The greedy choice for fractional knapsack is…

A. Highest value/weight ratio first. Sorting by ratio is the O(n log n) step.

Q. Does the same greedy rule solve 0/1 knapsack optimally?

A. No, 0/1 knapsack needs DP. Without fractions, a high-ratio item can waste capacity.

Program 16

Job sequencing with deadlines

Write a program in c to solve the job sequencing with deadlines problem using the greedy method and find its execution time using the time function.

Run it

Algorithm

Algorithm: JobSequencing(p, d, n)

1. Start
2. maxd <- largest deadline
3. For t <- 1 to maxd do
4.        slot[t] <- 0
5. Sort the jobs in decreasing order of profit p[i] (merge sort)
6. total <- 0
7. For each job i in sorted order do
8.        For t <- d[i] down to 1 do
9.              if slot[t] == 0 then
10.                   slot[t] <- i
11.                   total <- total + p[i]
12.                   break
13. print the jobs in slot[1..maxd] and total
14. Stop

Program

#include<stdio.h>
#include<time.h>

int p[50];
int count=0;

void merge(int a[],int low,int mid,int high) {
    int n1=mid-low+1,n2=high-mid;
    int left[n1],right[n2];
    int i,j,k;

    for(i=0;i<n1;i++)
        left[i]=a[low+i];
    for(j=0;j<n2;j++)
        right[j]=a[mid+1+j];

    i=0;
    j=0;
    k=low;
    while(i<n1 && j<n2) {
        count++;
        if(p[left[i]]>=p[right[j]])
            a[k++]=left[i++];
        else
            a[k++]=right[j++];
    }
    while(i<n1)
        a[k++]=left[i++];
    while(j<n2)
        a[k++]=right[j++];
}

void mergeSort(int a[],int low,int high) {
    if(low<high) {
        int mid=(low+high)/2;
        mergeSort(a,low,mid);
        mergeSort(a,mid+1,high);
        merge(a,low,mid,high);
    }
}

int main() {
    int n,i,k,t,maxd=0,total=0;
    printf("Enter the number of jobs:");
    scanf("%d",&n);
    int d[n+1],order[n];
    printf("Enter the profits of %d jobs:",n);
    for(i=1;i<=n;i++)
        scanf("%d",&p[i]);
    printf("Enter the deadlines of %d jobs:",n);
    for(i=1;i<=n;i++) {
        scanf("%d",&d[i]);
        if(d[i]>maxd)
            maxd=d[i];
    }
    int slot[maxd+1];

    clock_t start=clock();
    for(i=1;i<=n;i++)
        order[i-1]=i;
    for(t=1;t<=maxd;t++)
        slot[t]=0;
    mergeSort(order,0,n-1);
    for(k=0;k<n;k++) {
        i=order[k];
        for(t=d[i];t>=1;t--) {
            count++;
            if(slot[t]==0) {
                slot[t]=i;
                total=total+p[i];
                break;
            }
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nJobs in decreasing order of profit:\nJob\tProfit\tDeadline");
    for(k=0;k<n;k++) {
        i=order[k];
        printf("\nJ%d\t%d\t%d",i,p[i],d[i]);
    }
    printf("\nJob sequence:");
    for(t=1;t<=maxd;t++)
        if(slot[t]!=0)
            printf("\tJ%d",slot[t]);
    printf("\nMaximum profit:%d",total);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n^2)");
    printf("\nSpace complexity: O(n)");
    printf("\n");
    return 0;
}

Output

Input typed: 5 ⏎ 100 19 27 25 15 ⏎ 2 1 2 1 3

Enter the number of jobs:5
Enter the profits of 5 jobs:100 19 27 25 15
Enter the deadlines of 5 jobs:2 1 2 1 3

Jobs in decreasing order of profit:
Job	Profit	Deadline
J1	100	2
J3	27	2
J4	25	1
J2	19	1
J5	15	3
Job sequence:	J3	J1	J5
Maximum profit:142
Number of comparisons:14
Time taken:0.000003 seconds
Time complexity: O(n^2)
Space complexity: O(n)

Complexity

Time complexity: O(n^2)
Space complexity: O(n)
Best caseO(n log n)
Average caseO(n²)
Worst caseO(n²)
ParadigmGreedy

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int p[50];

    Declares the variables used below.

  2. int count=0;

    Declares the variables used below. count tallies the basic operations (comparisons/steps) to show the complexity.

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

    This line defines a function. merge() combines two sorted halves into one sorted run. low is the left end of the current search or sort range.

  4. int n1=mid-low+1,n2=high-mid;

    Declares the variables used below. mid = (low + high) / 2 splits the range in half. low is the left end of the current search or sort range.

  5. int left[n1],right[n2];

    Declares the variables used below. left is the start index of the left half (or the left child). right is the end index of the right half (or the right child).

  6. int i,j,k;

    Declares the variables used below.

  7. for(i=0;i<n1;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  8. left[i]=a[low+i];

    left is the start index of the left half (or the left child). low is the left end of the current search or sort range.

  9. for(j=0;j<n2;j++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  10. right[j]=a[mid+1+j];

    right is the end index of the right half (or the right child). mid = (low + high) / 2 splits the range in half.

  11. i=0;

    i is the loop counter.

  12. j=0;

    j is the inner loop counter.

  13. k=low;

    low is the left end of the current search or sort range.

  14. while(i<n1 && j<n2) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  15. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  16. if(p[left[i]]>=p[right[j]])

    This line is a decision. if runs the block only when the condition is true. left is the start index of the left half (or the left child).

  17. a[k++]=left[i++];

    a is the array being searched or sorted. left is the start index of the left half (or the left child).

  18. a[k++]=right[j++];

    a is the array being searched or sorted. right is the end index of the right half (or the right child).

  19. while(i<n1)

    This line is a while loop. while (condition) repeats as long as the condition is true.

  20. while(j<n2)

    This line is a while loop. while (condition) repeats as long as the condition is true.

  21. void mergeSort(int a[],int low,int high) {

    This line defines a function. mergeSort() splits the array in half, sorts each half recursively, then merges. low is the left end of the current search or sort range.

  22. if(low<high) {

    This line is a decision. if runs the block only when the condition is true. low is the left end of the current search or sort range.

  23. int mid=(low+high)/2;

    mid = (low + high) / 2 splits the range in half. low is the left end of the current search or sort range. high is the right end of the current range.

  24. mergeSort(a,low,mid);

    mergeSort() splits the array in half, sorts each half recursively, then merges. low is the left end of the current search or sort range. mid = (low + high) / 2 splits the range in half.

  25. mergeSort(a,mid+1,high);

    mergeSort() splits the array in half, sorts each half recursively, then merges. mid = (low + high) / 2 splits the range in half. high is the right end of the current range.

  26. merge(a,low,mid,high);

    merge() combines two sorted halves into one sorted run. low is the left end of the current search or sort range. mid = (low + high) / 2 splits the range in half.

  27. int main() {

    This line defines a function. main() is where the program starts running.

  28. int n,i,k,t,maxd=0,total=0;

    Declares the variables used below. n is the number of elements (or processes). maxd is the latest deadline, which sets how many slots exist.

  29. printf("Enter the number of jobs:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  30. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  31. int d[n+1],order[n];

    Declares the variables used below. n is the number of elements (or processes). order stores the sequence in which nodes are visited.

  32. printf("Enter the profits of %d jobs:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  35. printf("Enter the deadlines of %d jobs:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  36. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  38. if(d[i]>maxd)

    This line is a decision. if runs the block only when the condition is true. maxd is the latest deadline, which sets how many slots exist.

  39. maxd=d[i];

    maxd is the latest deadline, which sets how many slots exist.

  40. int slot[maxd+1];

    Declares the variables used below. slot marks which time slots are already filled. maxd is the latest deadline, which sets how many slots exist.

  41. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  42. order[i-1]=i;

    order stores the sequence in which nodes are visited.

  43. for(t=1;t<=maxd;t++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. maxd is the latest deadline, which sets how many slots exist.

  44. slot[t]=0;

    slot marks which time slots are already filled.

  45. mergeSort(order,0,n-1);

    mergeSort() splits the array in half, sorts each half recursively, then merges. order stores the sequence in which nodes are visited. n is the number of elements (or processes).

  46. for(k=0;k<n;k++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  47. i=order[k];

    i is the loop counter. order stores the sequence in which nodes are visited.

  48. for(t=d[i];t>=1;t--) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  49. if(slot[t]==0) {

    This line is a decision. if runs the block only when the condition is true. slot marks which time slots are already filled.

  50. slot[t]=i;

    slot marks which time slots are already filled.

  51. total=total+p[i];

    total accumulates the running sum (cost, value or weight).

  52. break;

    break leaves the nearest loop (or switch) immediately.

  53. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  54. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  55. printf("\nJobs in decreasing order of profit:\nJob\tProfit\tDeadline");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  56. printf("\nJ%d\t%d\t%d",i,p[i],d[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  57. printf("\nJob sequence:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  58. if(slot[t]!=0)

    This line is a decision. if runs the block only when the condition is true. slot marks which time slots are already filled.

  59. printf("\tJ%d",slot[t]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). slot marks which time slots are already filled.

  60. printf("\nMaximum profit:%d",total);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). total accumulates the running sum (cost, value or weight).

  61. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  62. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  63. printf("\nTime complexity: O(n^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  64. printf("\nSpace complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  65. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  66. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Job sequencing with deadlines?

A. Best O(n log n), average O(n²), worst O(n²). Design paradigm: Greedy.

Q. Job sequencing greedily picks jobs by…

A. Highest profit first, put in the latest free slot before its deadline. Each job takes one unit of time.

Program 17

Huffman coding

Write a program in c to construct an optimal prefix code using Huffman coding (greedy method) and find its execution time using the time function.

Run it

Algorithm

Algorithm: Huffman(C, f, n)

1. Start
2. Q <- min-priority queue of all n characters, keyed on frequency f
3. For i <- 1 to (n-1) do
4.        allocate a new node z
5.        x <- ExtractMin(Q)
6.        y <- ExtractMin(Q)
7.        left[z] <- x
8.        right[z] <- y
9.        f[z] <- f[x] + f[y]
10.       Insert(Q, z)
11. root <- ExtractMin(Q)
12. PrintCodes(root, "")
13. Stop

Algorithm: PrintCodes(z, code)

1. If z is a leaf then
2.        print character of z and code
3.        Return
4. PrintCodes(left[z], code + "0")
5. PrintCodes(right[z], code + "1")

Program

#include<stdio.h>
#include<time.h>

char ch[100];
int f[100],lft[100],rgt[100];
int Q[100],qsize=0,comp=0;
int code[100];

void heapify(int i) {
    int smallest=i,l=2*i+1,r=2*i+2;
    if(l<qsize) {
        comp++;
        if(f[Q[l]]<f[Q[smallest]])
            smallest=l;
    }
    if(r<qsize) {
        comp++;
        if(f[Q[r]]<f[Q[smallest]])
            smallest=r;
    }
    if(smallest!=i) {
        int t=Q[i];
        Q[i]=Q[smallest];
        Q[smallest]=t;
        heapify(smallest);
    }
}

int extractMin() {
    int min=Q[0];
    Q[0]=Q[qsize-1];
    qsize--;
    heapify(0);
    return min;
}

void insert(int z) {
    int i=qsize;
    Q[qsize++]=z;
    while(i>0) {
        int p=(i-1)/2;
        comp++;
        if(f[Q[i]]>=f[Q[p]])
            break;
        int t=Q[i];
        Q[i]=Q[p];
        Q[p]=t;
        i=p;
    }
}

void printCodes(int z,int depth) {
    int i;
    if(lft[z]==-1 && rgt[z]==-1) {
        printf("\n%c\t%d\t",ch[z],f[z]);
        if(depth==0)
            printf("0");
        for(i=0;i<depth;i++)
            printf("%d",code[i]);
        return;
    }
    code[depth]=0;
    printCodes(lft[z],depth+1);
    code[depth]=1;
    printCodes(rgt[z],depth+1);
}

int main() {
    int n,i;
    printf("Enter the number of characters:");
    scanf("%d",&n);
    printf("Enter the %d characters:",n);
    for(i=0;i<n;i++)
        scanf(" %c",&ch[i]);
    printf("Enter the frequencies of %d characters:",n);
    for(i=0;i<n;i++) {
        scanf("%d",&f[i]);
        lft[i]=rgt[i]=-1;
    }

    clock_t start=clock();
    for(i=0;i<n;i++)
        insert(i);
    int next=n;
    for(i=1;i<=n-1;i++) {
        int z=next++;
        int x=extractMin();
        int y=extractMin();
        lft[z]=x;
        rgt[z]=y;
        f[z]=f[x]+f[y];
        insert(z);
    }
    int root=extractMin();
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nHuffman codes:\nChar\tFreq\tCode");
    printCodes(root,0);
    printf("\nTotal frequency at root:%d",f[root]);
    printf("\nNumber of comparisons:%d",comp);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n log n)");
    printf("\nSpace complexity: O(n)");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ a b c d e f ⏎ 45 13 12 16 9 5

Enter the number of characters:6
Enter the 6 characters:a b c d e f
Enter the frequencies of 6 characters:45 13 12 16 9 5

Huffman codes:
Char	Freq	Code
a	45	0
c	12	100
b	13	101
f	5	1100
e	9	1101
d	16	111
Total frequency at root:100
Number of comparisons:27
Time taken:0.000005 seconds
Time complexity: O(n log n)
Space complexity: O(n)

Complexity

Time complexity: O(n log n)
Space complexity: O(n)
Best caseO(n log n)
Average caseO(n log n)
Worst caseO(n log n)
ParadigmGreedy

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. char ch[100];

    Declares the variables used below.

  2. int f[100],lft[100],rgt[100];

    Declares the variables used below. lft is the left subtree/child. rgt is the right subtree/child.

  3. int Q[100],qsize=0,comp=0;

    Declares the variables used below. qsize is how many items are in the queue. comp counts comparisons, the basic operation being measured.

  4. int code[100];

    Declares the variables used below. code builds the Huffman bit string on the way down the tree.

  5. void heapify(int i) {

    This line defines a function. heapify() pushes a node down until the max-heap property holds.

  6. int smallest=i,l=2*i+1,r=2*i+2;

    Declares the variables used below. smallest is the index of the minimum in the unsorted part.

  7. if(l<qsize) {

    This line is a decision. if runs the block only when the condition is true. qsize is how many items are in the queue.

  8. comp++;

    Counts one more basic operation. comp counts comparisons, the basic operation being measured.

  9. if(f[Q[l]]<f[Q[smallest]])

    This line is a decision. if runs the block only when the condition is true. smallest is the index of the minimum in the unsorted part.

  10. smallest=l;

    smallest is the index of the minimum in the unsorted part.

  11. if(r<qsize) {

    This line is a decision. if runs the block only when the condition is true. qsize is how many items are in the queue.

  12. if(f[Q[r]]<f[Q[smallest]])

    This line is a decision. if runs the block only when the condition is true. smallest is the index of the minimum in the unsorted part.

  13. smallest=r;

    smallest is the index of the minimum in the unsorted part.

  14. if(smallest!=i) {

    This line is a decision. if runs the block only when the condition is true. smallest is the index of the minimum in the unsorted part.

  15. int t=Q[i];

    Declares the variables used below.

  16. Q[i]=Q[smallest];

    i is the loop counter. smallest is the index of the minimum in the unsorted part.

  17. Q[smallest]=t;

    smallest is the index of the minimum in the unsorted part.

  18. heapify(smallest);

    heapify() pushes a node down until the max-heap property holds. smallest is the index of the minimum in the unsorted part.

  19. int extractMin() {

    This line defines a function. extractMin() removes the smallest item from the priority queue.

  20. int min=Q[0];

    Declares the variables used below. min tracks the smallest value (or its index) found so far.

  21. Q[0]=Q[qsize-1];

    qsize is how many items are in the queue.

  22. qsize--;

    qsize is how many items are in the queue.

  23. heapify(0);

    heapify() pushes a node down until the max-heap property holds.

  24. return min;

    This line returns from the function. return exits the function and hands back a value. min tracks the smallest value (or its index) found so far.

  25. void insert(int z) {

    This line defines a function. insert() adds an element and restores the structure's order.

  26. int i=qsize;

    Declares the variables used below. qsize is how many items are in the queue.

  27. Q[qsize++]=z;

    qsize is how many items are in the queue.

  28. while(i>0) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  29. int p=(i-1)/2;

    i is the loop counter.

  30. if(f[Q[i]]>=f[Q[p]])

    This line is a decision. if runs the block only when the condition is true.

  31. break;

    break leaves the nearest loop (or switch) immediately.

  32. Q[i]=Q[p];

    i is the loop counter.

  33. i=p;

    i is the loop counter.

  34. void printCodes(int z,int depth) {

    This line defines a function. printCodes() walks the Huffman tree: left adds 0, right adds 1. depth is how far the recursion/search has gone.

  35. int i;

    Declares the variables used below.

  36. if(lft[z]==-1 && rgt[z]==-1) {

    This line is a decision. if runs the block only when the condition is true. lft is the left subtree/child.

  37. printf("\n%c\t%d\t",ch[z],f[z]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  38. if(depth==0)

    This line is a decision. if runs the block only when the condition is true. depth is how far the recursion/search has gone.

  39. printf("0");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  40. for(i=0;i<depth;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. depth is how far the recursion/search has gone.

  41. printf("%d",code[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). code builds the Huffman bit string on the way down the tree.

  42. return;

    This line returns from the function. return exits the function and hands back a value.

  43. code[depth]=0;

    code builds the Huffman bit string on the way down the tree. depth is how far the recursion/search has gone.

  44. printCodes(lft[z],depth+1);

    printCodes() walks the Huffman tree: left adds 0, right adds 1. lft is the left subtree/child. depth is how far the recursion/search has gone.

  45. code[depth]=1;

    code builds the Huffman bit string on the way down the tree. depth is how far the recursion/search has gone.

  46. printCodes(rgt[z],depth+1);

    printCodes() walks the Huffman tree: left adds 0, right adds 1. rgt is the right subtree/child. depth is how far the recursion/search has gone.

  47. int main() {

    This line defines a function. main() is where the program starts running.

  48. int n,i;

    Declares the variables used below. n is the number of elements (or processes).

  49. printf("Enter the number of characters:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  50. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  51. printf("Enter the %d characters:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  53. scanf(" %c",&ch[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  54. printf("Enter the frequencies of %d characters:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  55. for(i=0;i<n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  56. scanf("%d",&f[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  57. lft[i]=rgt[i]=-1;

    lft is the left subtree/child. rgt is the right subtree/child.

  58. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  59. insert(i);

    insert() adds an element and restores the structure's order.

  60. int next=n;

    Declares the variables used below. next points to the following element. n is the number of elements (or processes).

  61. for(i=1;i<=n-1;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  62. int z=next++;

    Declares the variables used below. next points to the following element.

  63. int x=extractMin();

    extractMin() removes the smallest item from the priority queue.

  64. int y=extractMin();

    extractMin() removes the smallest item from the priority queue.

  65. lft[z]=x;

    lft is the left subtree/child.

  66. rgt[z]=y;

    rgt is the right subtree/child.

  67. insert(z);

    insert() adds an element and restores the structure's order.

  68. int root=extractMin();

    root is the top node of the tree. extractMin() removes the smallest item from the priority queue.

  69. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  70. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  71. printf("\nHuffman codes:\nChar\tFreq\tCode");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  72. printCodes(root,0);

    printCodes() walks the Huffman tree: left adds 0, right adds 1. root is the top node of the tree.

  73. printf("\nTotal frequency at root:%d",f[root]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). root is the top node of the tree.

  74. printf("\nNumber of comparisons:%d",comp);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). comp counts comparisons, the basic operation being measured.

  75. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  76. printf("\nTime complexity: O(n log n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  77. printf("\nSpace complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  78. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  79. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Huffman coding?

A. Best O(n log n), average O(n log n), worst O(n log n). Design paradigm: Greedy.

Q. Huffman coding repeatedly merges…

A. The two lowest-frequency nodes. So frequent characters end up with short codes.

Q. Huffman codes are prefix codes, meaning…

A. No code is the start of another code. That makes decoding unambiguous.

Backtracking & B&B

Program 18

N-Queen

Write a program in c to solve the N-Queen problem using backtracking and find its execution time using the time function.

Run it

Algorithm

Algorithm: Place(k, i)
(returns true if a queen can be placed in row k, column i)

1. For j <- 1 to (k-1) do
2.        if x[j] == i or |x[j] - i| == |j - k| then
3.              Return false
4. Return true

Algorithm: NQueens(k, n)

1. Start
2. For i <- 1 to n do
3.        if Place(k, i) then
4.              x[k] <- i
5.              if k == n then
6.                    print x[1..n]
7.              else
8.                    NQueens(k+1, n)
9. Stop

Program

#include<stdio.h>
#include<time.h>

int x[20],first[20];
int n,solutions=0,comp=0;

int place(int k,int i) {
    int j;
    for(j=1;j<k;j++) {
        comp++;
        if(x[j]==i || x[j]-i==j-k || x[j]-i==k-j)
            return 0;
    }
    return 1;
}

void nQueens(int k) {
    int i,j;
    for(i=1;i<=n;i++) {
        if(place(k,i)) {
            x[k]=i;
            if(k==n) {
                solutions++;
                printf("\nSolution %d:",solutions);
                for(j=1;j<=n;j++)
                    printf("\t%d",x[j]);
                if(solutions==1)
                    for(j=1;j<=n;j++)
                        first[j]=x[j];
            }
            else
                nQueens(k+1);
        }
    }
}

int main() {
    int i,j;
    printf("Enter the number of queens:");
    scanf("%d",&n);

    printf("\nColumn of the queen in each row 1..%d:",n);
    clock_t start=clock();
    nQueens(1);
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    if(solutions>0) {
        printf("\n\nBoard for solution 1:");
        for(i=1;i<=n;i++) {
            printf("\n");
            for(j=1;j<=n;j++)
                if(first[i]==j)
                    printf("Q ");
                else
                    printf(". ");
        }
    }
    printf("\nTotal solutions:%d",solutions);
    printf("\nNumber of comparisons:%d",comp);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n!)");
    printf("\nSpace complexity: O(n)");
    printf("\n");
    return 0;
}

Output

Input typed: 4

Enter the number of queens:4

Column of the queen in each row 1..4:
Solution 1:	2	4	1	3
Solution 2:	3	1	4	2

Board for solution 1:
. Q . .
. . . Q
Q . . .
. . Q .
Total solutions:2
Number of comparisons:84
Time taken:0.000008 seconds
Time complexity: O(n!)
Space complexity: O(n)

Complexity

Time complexity: O(n!)
Space complexity: O(n)
Best caseO(n!)
Average caseO(n!)
Worst caseO(n!)
ParadigmBacktracking

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int x[20],first[20];

    Declares the variables used below. first marks the first item (or the first fit found).

  2. int n,solutions=0,comp=0;

    Declares the variables used below. n is the number of elements (or processes). solutions counts the valid boards found.

  3. int place(int k,int i) {

    This line defines a function. place() checks that no earlier queen shares a column or diagonal.

  4. int j;

    Declares the variables used below.

  5. for(j=1;j<k;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  6. comp++;

    Counts one more basic operation. comp counts comparisons, the basic operation being measured.

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

    This line is a decision. if runs the block only when the condition is true.

  8. return 0;

    This line returns from the function. return exits the function and hands back a value.

  9. return 1;

    This line returns from the function. return exits the function and hands back a value.

  10. void nQueens(int k) {

    This line defines a function. nQueens() places one queen per row and backtracks on a clash.

  11. int i,j;

    Declares the variables used below.

  12. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  13. if(place(k,i)) {

    This line is a decision. if runs the block only when the condition is true. place() checks that no earlier queen shares a column or diagonal.

  14. x[k]=i;

    i is the loop counter.

  15. if(k==n) {

    This line is a decision. if runs the block only when the condition is true. n is the number of elements (or processes).

  16. solutions++;

    solutions counts the valid boards found.

  17. printf("\nSolution %d:",solutions);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). solutions counts the valid boards found.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  19. printf("\t%d",x[j]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  20. if(solutions==1)

    This line is a decision. if runs the block only when the condition is true. solutions counts the valid boards found.

  21. first[j]=x[j];

    first marks the first item (or the first fit found).

  22. nQueens(k+1);

    nQueens() places one queen per row and backtracks on a clash.

  23. int main() {

    This line defines a function. main() is where the program starts running.

  24. printf("Enter the number of queens:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  25. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  26. printf("\nColumn of the queen in each row 1..%d:",n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  27. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  28. nQueens(1);

    nQueens() places one queen per row and backtracks on a clash.

  29. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  30. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  31. if(solutions>0) {

    This line is a decision. if runs the block only when the condition is true. solutions counts the valid boards found.

  32. printf("\n\nBoard for solution 1:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  33. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  34. if(first[i]==j)

    This line is a decision. if runs the block only when the condition is true. first marks the first item (or the first fit found).

  35. printf("Q ");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  36. printf(". ");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  37. printf("\nTotal solutions:%d",solutions);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). solutions counts the valid boards found.

  38. printf("\nNumber of comparisons:%d",comp);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). comp counts comparisons, the basic operation being measured.

  39. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  40. printf("\nTime complexity: O(n!)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  41. printf("\nSpace complexity: O(n)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

Viva: concepts

Q. What is the time complexity of N-Queen?

A. Best O(n!), average O(n!), worst O(n!). Design paradigm: Backtracking.

Q. Backtracking means…

A. Undo the last choice when it leads to a dead end. Place a queen; if no safe column remains in the next row, move the previous queen.

Q. Two queens at (i, a) and (j, b) attack diagonally when…

A. |i − j| = |a − b|. That is the place() check, together with a ≠ b.

Q. How many solutions does 4-Queen have?

A. 2. 8-Queen has 92.

Program 22

Job assignment (branch & bound)

Write a program in c to solve the job assignment problem using branch and bound and find its execution time using the time function.

Run it

Algorithm

Algorithm: JOB-ASSIGNMENT(C, n)   (Least Cost Branch and Bound)
(lb(X) = cost of the jobs assigned so far in X
         + for every worker not yet assigned, his cheapest job among the jobs still free)

1. Start
2. Create the root node: no worker assigned, cost <- 0
3. lb(root) <- lower bound of root
4. Insert root into the list of live nodes
5. While the list of live nodes is not empty do
6.       E <- the live node with minimum lb
7.       Remove E from the list of live nodes
8.       if all n workers are assigned in E then
9.             print the assignment in E and its cost as the optimal solution
10.            Stop
11.      i <- the next worker to be assigned in E
12.      For each job j not yet assigned in E do
13.            Create a child X of E with worker i assigned job j
14.            cost(X) <- cost(E) + C[i][j]
15.            lb(X) <- lower bound of X
16.            Insert X into the list of live nodes
17. Stop

Program

#include<stdio.h>
#include<time.h>
#define INF 99999
#define MAX 100000

int n,c[15][15],count=0,total=0;
int parent[MAX],level[MAX],job[MAX],used[MAX],cost[MAX],lb[MAX],live[MAX];

int bound(int k) {
    int i,j,min,b=cost[k];
    for(i=level[k]+1;i<=n;i++) {
        min=INF;
        for(j=1;j<=n;j++) {
            count++;
            if(!(used[k]&(1<<j)) && c[i][j]<min)
                min=c[i][j];
        }
        b+=min;
    }
    return b;
}

void new_node(int p,int j) {
    int k=total++;
    parent[k]=p;
    if(p==-1) {
        level[k]=0;
        job[k]=0;
        used[k]=0;
        cost[k]=0;
    }
    else {
        level[k]=level[p]+1;
        job[k]=j;
        used[k]=used[p]|(1<<j);
        cost[k]=cost[p]+c[level[k]][j];
    }
    lb[k]=bound(k);
    live[k]=1;
}

void assignment(int k) {
    if(parent[k]==-1) {
        printf("root");
        return;
    }
    if(parent[parent[k]]!=-1) {
        assignment(parent[k]);
        printf(", ");
    }
    printf("W%d->J%d",level[k],job[k]);
}

int main() {
    int i,j,k,E,ans=-1,expanded=0;
    printf("Enter the number of workers/jobs:");
    scanf("%d",&n);
    printf("Enter the %dx%d cost matrix (row = worker, column = job):\n",n,n);
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
            scanf("%d",&c[i][j]);

    int order[MAX],first[MAX];

    clock_t start=clock();
    new_node(-1,0);
    while(1) {
        E=-1;
        for(k=0;k<total;k++) {
            if(live[k]) {
                count++;
                if(E==-1 || lb[k]<lb[E])
                    E=k;
            }
        }
        if(E==-1)
            break;
        live[E]=0;
        if(level[E]==n) {
            ans=E;
            break;
        }
        order[expanded]=E;
        first[expanded]=total;
        expanded++;
        for(j=1;j<=n;j++)
            if(!(used[E]&(1<<j)))
                new_node(E,j);
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nNodes expanded (least lb first):");
    for(i=0;i<expanded;i++) {
        E=order[i];
        printf("\nE = {");
        assignment(E);
        printf("}  lb = %d",lb[E]);
        for(k=first[i];k<first[i]+n-level[E];k++)
            printf("\n      W%d->J%d   cost = %-4d lb = %d",level[k],job[k],cost[k],lb[k]);
    }

    printf("\n\nOptimal assignment:");
    for(i=1;i<=n;i++) {
        k=ans;
        while(level[k]!=i)
            k=parent[k];
        printf("\nWorker %d -> Job %d\tcost = %d",i,job[k],c[i][job[k]]);
    }
    printf("\nMinimum total cost:%d",cost[ans]);
    printf("\nNodes generated:%d",total);
    printf("\nNodes expanded:%d",expanded);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(n!) in the worst case, far less when the bound prunes the tree");
    printf("\nSpace complexity: O(n!) in the worst case for the live nodes");
    printf("\n");
    return 0;
}

Output

Input typed: 4 ⏎ 9 2 7 8 ⏎ 6 4 3 7 ⏎ 5 8 1 8 ⏎ 7 6 9 4

Enter the number of workers/jobs:4
Enter the 4x4 cost matrix (row = worker, column = job):
9 2 7 8
6 4 3 7
5 8 1 8
7 6 9 4

Nodes expanded (least lb first):
E = {root}  lb = 10
      W1->J1   cost = 9    lb = 17
      W1->J2   cost = 2    lb = 10
      W1->J3   cost = 7    lb = 20
      W1->J4   cost = 8    lb = 18
E = {W1->J2}  lb = 10
      W2->J1   cost = 8    lb = 13
      W2->J3   cost = 5    lb = 14
      W2->J4   cost = 9    lb = 17
E = {W1->J2, W2->J1}  lb = 13
      W3->J3   cost = 9    lb = 13
      W3->J4   cost = 16   lb = 25
E = {W1->J2, W2->J1, W3->J3}  lb = 13
      W4->J4   cost = 13   lb = 13

Optimal assignment:
Worker 1 -> Job 2	cost = 2
Worker 2 -> Job 1	cost = 6
Worker 3 -> Job 3	cost = 1
Worker 4 -> Job 4	cost = 4
Minimum total cost:13
Nodes generated:11
Nodes expanded:4
Number of comparisons:121
Time taken:0.000009 seconds
Time complexity: O(n!) in the worst case, far less when the bound prunes the tree
Space complexity: O(n!) in the worst case for the live nodes

Complexity

Time complexity: O(n!) in the worst case, far less when the bound prunes the tree
Space complexity: O(n!) in the worst case for the live nodes
Best caseO(n²)
Average caseO(n!)
Worst caseO(n!)
ParadigmBranch & bound

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. #define INF 99999

    INF stands for 'no edge / unreachable' (a very large number).

  2. #define MAX 100000

    MAX is the array size limit set with #define.

  3. int n,c[15][15],count=0,total=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  4. int parent[MAX],level[MAX],job[MAX],used[MAX],cost[MAX],lb[MAX],live[MAX];

    Declares the variables used below. parent records each node's predecessor, used to rebuild the tree or path. MAX is the array size limit set with #define.

  5. int bound(int k) {

    This line defines a function. bound is the best value this branch could still reach (branch and bound).

  6. int i,j,min,b=cost[k];

    Declares the variables used below. min tracks the smallest value (or its index) found so far. cost holds the edge weights (the adjacency/cost matrix).

  7. for(i=level[k]+1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. level is the BFS depth (distance in edges from the start).

  8. min=INF;

    min tracks the smallest value (or its index) found so far. INF stands for 'no edge / unreachable' (a very large number).

  9. for(j=1;j<=n;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  10. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  11. if(!(used[k]&(1<<j)) && c[i][j]<min)

    This line is a decision. if runs the block only when the condition is true. used marks items or columns already taken.

  12. min=c[i][j];

    min tracks the smallest value (or its index) found so far.

  13. b+=min;

    min tracks the smallest value (or its index) found so far.

  14. return b;

    This line returns from the function. return exits the function and hands back a value.

  15. void new_node(int p,int j) {

    This line defines a function. new_node() allocates and fills a tree/list node.

  16. int k=total++;

    Declares the variables used below. total accumulates the running sum (cost, value or weight).

  17. parent[k]=p;

    parent records each node's predecessor, used to rebuild the tree or path.

  18. if(p==-1) {

    This line is a decision. if runs the block only when the condition is true.

  19. level[k]=0;

    level is the BFS depth (distance in edges from the start).

  20. job[k]=0;

    job is a task with a deadline and profit in job sequencing.

  21. used[k]=0;

    used marks items or columns already taken.

  22. cost[k]=0;

    cost holds the edge weights (the adjacency/cost matrix).

  23. else {

    This line is a decision. else runs when the if condition was false.

  24. level[k]=level[p]+1;

    level is the BFS depth (distance in edges from the start).

  25. job[k]=j;

    job is a task with a deadline and profit in job sequencing.

  26. used[k]=used[p]|(1<<j);

    used marks items or columns already taken.

  27. cost[k]=cost[p]+c[level[k]][j];

    cost holds the edge weights (the adjacency/cost matrix). level is the BFS depth (distance in edges from the start).

  28. lb[k]=bound(k);

    bound is the best value this branch could still reach (branch and bound).

  29. live[k]=1;

    live nodes are the branches still waiting to be expanded.

  30. void assignment(int k) {

    This line defines a function. assignment stores which task each worker gets.

  31. if(parent[k]==-1) {

    This line is a decision. if runs the block only when the condition is true. parent records each node's predecessor, used to rebuild the tree or path.

  32. printf("root");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  33. return;

    This line returns from the function. return exits the function and hands back a value.

  34. if(parent[parent[k]]!=-1) {

    This line is a decision. if runs the block only when the condition is true. parent records each node's predecessor, used to rebuild the tree or path.

  35. assignment(parent[k]);

    assignment stores which task each worker gets. parent records each node's predecessor, used to rebuild the tree or path.

  36. printf(", ");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  37. printf("W%d->J%d",level[k],job[k]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). level is the BFS depth (distance in edges from the start).

  38. int main() {

    This line defines a function. main() is where the program starts running.

  39. int i,j,k,E,ans=-1,expanded=0;

    Declares the variables used below. ans holds the best answer found so far. expanded counts how many nodes branch-and-bound opened.

  40. printf("Enter the number of workers/jobs:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  41. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  42. printf("Enter the %dx%d cost matrix (row = worker, column = job):\n",n,n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  46. int order[MAX],first[MAX];

    Declares the variables used below. order stores the sequence in which nodes are visited. MAX is the array size limit set with #define.

  47. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  48. new_node(-1,0);

    new_node() allocates and fills a tree/list node.

  49. while(1) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  50. for(k=0;k<total;k++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. total accumulates the running sum (cost, value or weight).

  51. if(live[k]) {

    This line is a decision. if runs the block only when the condition is true. live nodes are the branches still waiting to be expanded.

  52. if(E==-1 || lb[k]<lb[E])

    This line is a decision. if runs the block only when the condition is true.

  53. if(E==-1)

    This line is a decision. if runs the block only when the condition is true.

  54. break;

    break leaves the nearest loop (or switch) immediately.

  55. live[E]=0;

    live nodes are the branches still waiting to be expanded.

  56. if(level[E]==n) {

    This line is a decision. if runs the block only when the condition is true. level is the BFS depth (distance in edges from the start).

  57. ans=E;

    ans holds the best answer found so far.

  58. order[expanded]=E;

    order stores the sequence in which nodes are visited. expanded counts how many nodes branch-and-bound opened.

  59. first[expanded]=total;

    first marks the first item (or the first fit found). expanded counts how many nodes branch-and-bound opened. total accumulates the running sum (cost, value or weight).

  60. expanded++;

    expanded counts how many nodes branch-and-bound opened.

  61. if(!(used[E]&(1<<j)))

    This line is a decision. if runs the block only when the condition is true. used marks items or columns already taken.

  62. new_node(E,j);

    new_node() allocates and fills a tree/list node.

  63. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  64. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  65. printf("\nNodes expanded (least lb first):");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  66. for(i=0;i<expanded;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. expanded counts how many nodes branch-and-bound opened.

  67. E=order[i];

    order stores the sequence in which nodes are visited.

  68. printf("\nE = {");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  69. assignment(E);

    assignment stores which task each worker gets.

  70. printf("}  lb = %d",lb[E]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  71. for(k=first[i];k<first[i]+n-level[E];k++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. first marks the first item (or the first fit found).

  72. printf("\n      W%d->J%d   cost = %-4d lb = %d",level[k],job[k],cost[k],lb[k]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). level is the BFS depth (distance in edges from the start).

  73. printf("\n\nOptimal assignment:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  74. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  75. k=ans;

    ans holds the best answer found so far.

  76. while(level[k]!=i)

    This line is a while loop. while (condition) repeats as long as the condition is true. level is the BFS depth (distance in edges from the start).

  77. k=parent[k];

    parent records each node's predecessor, used to rebuild the tree or path.

  78. printf("\nWorker %d -> Job %d\tcost = %d",i,job[k],c[i][job[k]]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). job is a task with a deadline and profit in job sequencing.

  79. printf("\nMinimum total cost:%d",cost[ans]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). cost holds the edge weights (the adjacency/cost matrix).

  80. printf("\nNodes generated:%d",total);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). total accumulates the running sum (cost, value or weight).

  81. printf("\nNodes expanded:%d",expanded);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). expanded counts how many nodes branch-and-bound opened.

  82. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  83. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  84. printf("\nTime complexity: O(n!) in the worst case, far less when the bound prunes the tree");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  85. printf("\nSpace complexity: O(n!) in the worst case for the live nodes");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  86. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  87. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Job assignment (branch & bound)?

A. Best O(n²), average O(n!), worst O(n!). Design paradigm: Branch & bound.

Q. Branch & bound prunes a node when…

A. Its lower bound is worse than the best solution found so far. The least-cost (lb) node is expanded next.

Q. Backtracking vs branch & bound:

A. B&B uses bounds to prune and usually BFS / least-cost order. Backtracking is DFS with feasibility checks.

Graphs

Program 20

Breadth-first search

Write a program in c to traverse a graph using breadth first search (BFS) and find its execution time using the time function.

Run it

Algorithm

Algorithm: BFS(G, s)

1. Start
2. For each vertex u in G do
3.        visited[u] <- 0
4.        d[u] <- infinity
5. visited[s] <- 1, d[s] <- 0
6. Enqueue(Q, s)
7. While Q is not empty do
8.        u <- Dequeue(Q)
9.        print u
10.       For each vertex v adjacent to u do
11.             if visited[v] == 0 then
12.                   visited[v] <- 1
13.                   d[v] <- d[u] + 1
14.                   Enqueue(Q, v)
15. Stop

Program

#include<stdio.h>
#include<time.h>

int main() {
    int n,i,u,v,s,front=0,rear=0,count=0;
    printf("Enter the number of vertices:");
    scanf("%d",&n);
    int adj[n+1][n+1],visited[n+1],d[n+1],Q[n];
    printf("Enter the %dx%d adjacency matrix:\n",n,n);
    for(u=1;u<=n;u++)
        for(v=1;v<=n;v++)
            scanf("%d",&adj[u][v]);
    printf("Enter the source vertex:");
    scanf("%d",&s);

    clock_t start=clock();
    for(u=1;u<=n;u++) {
        visited[u]=0;
        d[u]=-1;
    }
    visited[s]=1;
    d[s]=0;
    Q[rear++]=s;
    printf("\nBFS traversal:");
    while(front<rear) {
        u=Q[front++];
        printf("\t%d",u);
        for(v=1;v<=n;v++) {
            count++;
            if(adj[u][v]==1 && visited[v]==0) {
                visited[v]=1;
                d[v]=d[u]+1;
                Q[rear++]=v;
            }
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nVertex\tDistance from %d",s);
    for(i=1;i<=n;i++)
        if(d[i]==-1)
            printf("\n%d\tunreachable",i);
        else
            printf("\n%d\t%d",i,d[i]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");
    printf("\nSpace complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 0 1 1 0 0 0 ⏎ 1 0 0 1 1 0 ⏎ 1 0 0 0 1 0 ⏎ 0 1 0 0 0 1 ⏎ 0 1 1 0 0 1 ⏎ 0 0 0 1 1 0 ⏎ 1

Enter the number of vertices:6
Enter the 6x6 adjacency matrix:
0 1 1 0 0 0
1 0 0 1 1 0
1 0 0 0 1 0
0 1 0 0 0 1
0 1 1 0 0 1
0 0 0 1 1 0
Enter the source vertex:1

BFS traversal:	1	2	3	4	5	6
Vertex	Distance from 1
1	0
2	1
3	1
4	2
5	2
6	3
Number of comparisons:36
Time taken:0.000003 seconds
Time complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix
Space complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix

Complexity

Time complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix
Space complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix
Best caseO(V+E)
Average caseO(V+E)
Worst caseO(V+E)
ParadigmGraph traversal

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int main() {

    This line defines a function. main() is where the program starts running.

  2. int n,i,u,v,s,front=0,rear=0,count=0;

    Declares the variables used below. n is the number of elements (or processes). front is the index of the next item to dequeue.

  3. printf("Enter the number of vertices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  4. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  5. int adj[n+1][n+1],visited[n+1],d[n+1],Q[n];

    Declares the variables used below. adj is the adjacency matrix: adj[i][j] is non-zero when there is an edge i → j. n is the number of elements (or processes).

  6. printf("Enter the %dx%d adjacency matrix:\n",n,n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  7. for(u=1;u<=n;u++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  8. for(v=1;v<=n;v++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  9. scanf("%d",&adj[u][v]);

    This line reads input. scanf() reads input into variables; pass their addresses with &. adj is the adjacency matrix: adj[i][j] is non-zero when there is an edge i → j.

  10. printf("Enter the source vertex:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  11. scanf("%d",&s);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  12. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  13. for(u=1;u<=n;u++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  14. visited[u]=0;

    visited marks nodes already processed, so they are not repeated.

  15. visited[s]=1;

    visited marks nodes already processed, so they are not repeated.

  16. Q[rear++]=s;

    rear is where the next item is enqueued.

  17. printf("\nBFS traversal:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  18. while(front<rear) {

    This line is a while loop. while (condition) repeats as long as the condition is true. front is the index of the next item to dequeue.

  19. u=Q[front++];

    front is the index of the next item to dequeue.

  20. printf("\t%d",u);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  21. for(v=1;v<=n;v++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  22. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  23. if(adj[u][v]==1 && visited[v]==0) {

    This line is a decision. if runs the block only when the condition is true. adj is the adjacency matrix: adj[i][j] is non-zero when there is an edge i → j.

  24. visited[v]=1;

    visited marks nodes already processed, so they are not repeated.

  25. Q[rear++]=v;

    rear is where the next item is enqueued.

  26. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  27. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  28. printf("\nVertex\tDistance from %d",s);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  30. if(d[i]==-1)

    This line is a decision. if runs the block only when the condition is true.

  31. printf("\n%d\tunreachable",i);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  32. printf("\n%d\t%d",i,d[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  33. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  34. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  35. printf("\nTime complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  36. printf("\nSpace complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  37. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  38. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Breadth-first search?

A. Best O(V+E), average O(V+E), worst O(V+E). Design paradigm: Graph traversal.

Q. BFS uses which data structure?

A. A queue (FIFO). Visit level by level from the source.

Q. On an unweighted graph, BFS finds…

A. Shortest paths in number of edges. With an adjacency matrix it is O(V²).

Program 21

Depth-first search

Write a program in c to traverse a graph using depth first search (DFS) and find its execution time using the time function.

Run it

Algorithm

Algorithm: DFS(G, s)

1. Start
2. For each vertex u in G do
3.        visited[u] <- 0
4. time <- 0
5. DFS-Visit(s)
6. For each vertex u in G do
7.        if visited[u] == 0 then
8.              DFS-Visit(u)
9. Stop

Algorithm: DFS-Visit(u)

1. visited[u] <- 1
2. time <- time+1, d[u] <- time
3. print u
4. For each vertex v adjacent to u do
5.        if visited[v] == 0 then
6.              DFS-Visit(v)
7. time <- time+1, f[u] <- time

Program

#include<stdio.h>
#include<time.h>

int adj[50][50],visited[50],d[50],f[50];
int n,t=0,count=0;

void dfsVisit(int u) {
    int v;
    visited[u]=1;
    d[u]=++t;
    printf("\t%d",u);
    for(v=1;v<=n;v++) {
        count++;
        if(adj[u][v]==1 && visited[v]==0)
            dfsVisit(v);
    }
    f[u]=++t;
}

int main() {
    int u,v,s;
    printf("Enter the number of vertices:");
    scanf("%d",&n);
    printf("Enter the %dx%d adjacency matrix:\n",n,n);
    for(u=1;u<=n;u++)
        for(v=1;v<=n;v++)
            scanf("%d",&adj[u][v]);
    printf("Enter the source vertex:");
    scanf("%d",&s);

    clock_t start=clock();
    for(u=1;u<=n;u++)
        visited[u]=0;
    printf("\nDFS traversal:");
    dfsVisit(s);
    for(u=1;u<=n;u++)
        if(visited[u]==0)
            dfsVisit(u);
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nVertex\tDiscovery\tFinish");
    for(u=1;u<=n;u++)
        printf("\n%d\t%d\t\t%d",u,d[u],f[u]);
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");
    printf("\nSpace complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 0 1 1 0 0 0 ⏎ 1 0 0 1 1 0 ⏎ 1 0 0 0 1 0 ⏎ 0 1 0 0 0 1 ⏎ 0 1 1 0 0 1 ⏎ 0 0 0 1 1 0 ⏎ 1

Enter the number of vertices:6
Enter the 6x6 adjacency matrix:
0 1 1 0 0 0
1 0 0 1 1 0
1 0 0 0 1 0
0 1 0 0 0 1
0 1 1 0 0 1
0 0 0 1 1 0
Enter the source vertex:1

DFS traversal:	1	2	4	6	5	3
Vertex	Discovery	Finish
1	1		12
2	2		11
3	6		7
4	3		10
5	5		8
6	4		9
Number of comparisons:36
Time taken:0.000006 seconds
Time complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix
Space complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix

Complexity

Time complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix
Space complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix
Best caseO(V+E)
Average caseO(V+E)
Worst caseO(V+E)
ParadigmGraph traversal

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int adj[50][50],visited[50],d[50],f[50];

    Declares the variables used below. adj is the adjacency matrix: adj[i][j] is non-zero when there is an edge i → j. visited marks nodes already processed, so they are not repeated.

  2. int n,t=0,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  3. void dfsVisit(int u) {

    This line defines a function. dfsVisit() explores as deep as possible from a node before backtracking.

  4. int v;

    Declares the variables used below.

  5. visited[u]=1;

    visited marks nodes already processed, so they are not repeated.

  6. printf("\t%d",u);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  7. for(v=1;v<=n;v++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  8. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  9. if(adj[u][v]==1 && visited[v]==0)

    This line is a decision. if runs the block only when the condition is true. adj is the adjacency matrix: adj[i][j] is non-zero when there is an edge i → j.

  10. dfsVisit(v);

    dfsVisit() explores as deep as possible from a node before backtracking.

  11. int main() {

    This line defines a function. main() is where the program starts running.

  12. int u,v,s;

    Declares the variables used below.

  13. printf("Enter the number of vertices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  14. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  15. printf("Enter the %dx%d adjacency matrix:\n",n,n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  16. for(u=1;u<=n;u++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  17. for(v=1;v<=n;v++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  18. scanf("%d",&adj[u][v]);

    This line reads input. scanf() reads input into variables; pass their addresses with &. adj is the adjacency matrix: adj[i][j] is non-zero when there is an edge i → j.

  19. printf("Enter the source vertex:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  20. scanf("%d",&s);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  21. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  22. visited[u]=0;

    visited marks nodes already processed, so they are not repeated.

  23. printf("\nDFS traversal:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  24. dfsVisit(s);

    dfsVisit() explores as deep as possible from a node before backtracking.

  25. if(visited[u]==0)

    This line is a decision. if runs the block only when the condition is true. visited marks nodes already processed, so they are not repeated.

  26. dfsVisit(u);

    dfsVisit() explores as deep as possible from a node before backtracking.

  27. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  28. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  29. printf("\nVertex\tDiscovery\tFinish");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  30. printf("\n%d\t%d\t\t%d",u,d[u],f[u]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  31. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  32. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  33. printf("\nTime complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  34. printf("\nSpace complexity: O(V+E) with adjacency list, O(V^2) with adjacency matrix");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  35. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  36. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Depth-first search?

A. Best O(V+E), average O(V+E), worst O(V+E). Design paradigm: Graph traversal.

Q. DFS uses…

A. A stack (or recursion). Go as deep as possible, then backtrack.

Q. A common use of DFS is…

A. Cycle detection and topological sort. Also connected components.

Program 23

Dijkstra

Write a program in c to find the shortest path from a source vertex to all other vertices using Dijkstra's algorithm and find its execution time using the time function.

Run it

Algorithm

Algorithm: DA(G, w, s)

1. INITIALIZE-SINGLE-SOURCE(G, s)
2. S <- Ø
3. Q <- V[G]
4. while Q != Ø
5.       do u <- EXTRACT-MIN(Q)
6.          S <- S U {u}
7.          for each vertex v in Adj[u]
8.                do RELAX(u, v, w)

INITIALIZE-SINGLE-SOURCE(G, s)
1. for each vertex v in V[G]
2.       do d[v] <- infinity
3.          p[v] <- NIL
4. d[s] <- 0

EXTRACT-MIN(Q)
1. u <- the vertex in Q with minimum d[u]
2. Q <- Q - {u}
3. return u

RELAX(u, v, w)
1. if d[v] > d[u] + w(u,v)
2.       then d[v] <- d[u] + w(u,v)
3.            p[v] <- u

Program

#include<stdio.h>
#include<time.h>
#define INF 99999

int n,count=0;
int w[50][50],d[50],p[50],S[50],Q[50];

void initialize_single_source(int s) {
    int v;
    for(v=1;v<=n;v++) {
        d[v]=INF;
        p[v]=0;
    }
    d[s]=0;
}

int extract_min() {
    int v,u=0;
    for(v=1;v<=n;v++) {
        count++;
        if(Q[v]==1 && (u==0 || d[v]<d[u]))
            u=v;
    }
    Q[u]=0;
    return u;
}

void relax(int u,int v) {
    count++;
    if(d[v]>d[u]+w[u][v]) {
        d[v]=d[u]+w[u][v];
        p[v]=u;
    }
}

void path(int v) {
    if(p[v]==0) {
        printf("%d",v);
        return;
    }
    path(p[v]);
    printf(" -> %d",v);
}

int main() {
    int i,j,u,v,s,q_size,step=0;
    printf("Enter the number of vertices:");
    scanf("%d",&n);
    printf("Enter the %dx%d weight matrix (0 for no edge):\n",n,n);
    for(u=1;u<=n;u++)
        for(v=1;v<=n;v++)
            scanf("%d",&w[u][v]);
    printf("Enter the source vertex:");
    scanf("%d",&s);

    int order[n+1],pos[n+1],trace[n+1][n+1];
    char cell[12];

    clock_t start=clock();
    initialize_single_source(s);
    for(v=1;v<=n;v++)
        S[v]=0;
    for(v=1;v<=n;v++)
        Q[v]=1;
    q_size=n;
    while(q_size!=0) {
        u=extract_min();
        q_size--;
        S[u]=1;
        step++;
        order[step]=u;
        pos[u]=step;
        for(v=1;v<=n;v++)
            trace[step][v]=d[v];
        for(v=1;v<=n;v++)
            if(w[u][v]!=0)
                relax(u,v);
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nS = { }");
    printf("\nS = {%d}  (source, d[%d] = 0)\n",s,s);
    printf("\nu     ");
    for(v=1;v<=n;v++)
        if(v!=s)
            printf("%-6d",v);
    printf("S");
    for(i=2;i<=step;i++) {
        if(trace[i][order[i]]==INF)
            break;
        printf("\n%-6d",order[i]);
        for(v=1;v<=n;v++) {
            if(v==s)
                continue;
            if(trace[i][v]==INF)
                printf("%-6s","INF");
            else if(pos[v]<=i) {
                sprintf(cell,"(%d)",trace[i][v]);
                printf("%-6s",cell);
            }
            else
                printf("%-6d",trace[i][v]);
        }
        printf("{");
        for(j=1;j<=i;j++)
            printf(j==1?"%d":", %d",order[j]);
        printf("}");
    }
    printf("\n( ) = vertex is in S, its shortest distance is final");

    printf("\n\nVertex\tDistance\tPath");
    for(i=1;i<=n;i++) {
        if(d[i]==INF)
            printf("\n%d\tunreachable",i);
        else {
            printf("\n%d\t%d\t\t",i,d[i]);
            path(i);
        }
    }
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list");
    printf("\nSpace complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list");
    printf("\n");
    return 0;
}

Output

Input typed: 6 ⏎ 0 2 4 0 0 0 ⏎ 0 0 1 7 0 0 ⏎ 0 0 0 0 3 0 ⏎ 0 0 0 0 0 1 ⏎ 0 0 0 2 0 5 ⏎ 0 0 0 0 0 0 ⏎ 1

Enter the number of vertices:6
Enter the 6x6 weight matrix (0 for no edge):
0 2 4 0 0 0
0 0 1 7 0 0
0 0 0 0 3 0
0 0 0 0 0 1
0 0 0 2 0 5
0 0 0 0 0 0
Enter the source vertex:1
S = { }
S = {1}  (source, d[1] = 0)

u     2     3     4     5     6     S
2     (2)   4     INF   INF   INF   {1, 2}
3     (2)   (3)   9     INF   INF   {1, 2, 3}
5     (2)   (3)   9     (6)   INF   {1, 2, 3, 5}
4     (2)   (3)   (8)   (6)   11    {1, 2, 3, 5, 4}
6     (2)   (3)   (8)   (6)   (9)   {1, 2, 3, 5, 4, 6}
( ) = vertex is in S, its shortest distance is final

Vertex	Distance	Path
1	0		1
2	2		1 -> 2
3	3		1 -> 2 -> 3
4	8		1 -> 2 -> 3 -> 5 -> 4
5	6		1 -> 2 -> 3 -> 5
6	9		1 -> 2 -> 3 -> 5 -> 4 -> 6
Number of comparisons:44
Time taken:0.000002 seconds
Time complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list
Space complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list

Input typed: 6 ⏎ 0 50 45 10 0 0 ⏎ 0 0 10 15 0 0 ⏎ 0 0 0 0 30 0 ⏎ 20 0 0 0 15 0 ⏎ 0 20 35 0 0 0 ⏎ 0 0 0 0 3 0 ⏎ 1

Enter the number of vertices:6
Enter the 6x6 weight matrix (0 for no edge):
0 50 45 10 0 0
0 0 10 15 0 0
0 0 0 0 30 0
20 0 0 0 15 0
0 20 35 0 0 0
0 0 0 0 3 0
Enter the source vertex:1
S = { }
S = {1}  (source, d[1] = 0)

u     2     3     4     5     6     S
4     50    45    (10)  INF   INF   {1, 4}
5     50    45    (10)  (25)  INF   {1, 4, 5}
2     (45)  45    (10)  (25)  INF   {1, 4, 5, 2}
3     (45)  (45)  (10)  (25)  INF   {1, 4, 5, 2, 3}
( ) = vertex is in S, its shortest distance is final

Vertex	Distance	Path
1	0		1
2	45		1 -> 4 -> 5 -> 2
3	45		1 -> 3
4	10		1 -> 4
5	25		1 -> 4 -> 5
6	unreachable
Number of comparisons:47
Time taken:0.000002 seconds
Time complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list
Space complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list

Complexity

Time complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list
Space complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list
Best caseO(V²)
Average caseO(V²)
Worst caseO(V²)
ParadigmGreedy

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf, sprintf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. #define INF 99999

    INF stands for 'no edge / unreachable' (a very large number).

  2. int n,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  3. int w[50][50],d[50],p[50],S[50],Q[50];

    Declares the variables used below.

  4. void initialize_single_source(int s) {

    This line defines a function. initialize_single_source() sets every distance to ∞ and the source to 0.

  5. int v;

    Declares the variables used below.

  6. for(v=1;v<=n;v++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  7. d[v]=INF;

    INF stands for 'no edge / unreachable' (a very large number).

  8. int extract_min() {

    This line defines a function. extract_min() removes the node with the smallest key.

  9. int v,u=0;

    Declares the variables used below.

  10. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  11. if(Q[v]==1 && (u==0 || d[v]<d[u]))

    This line is a decision. if runs the block only when the condition is true.

  12. return u;

    This line returns from the function. return exits the function and hands back a value.

  13. void relax(int u,int v) {

    This line defines a function. relax() updates dist[v] if going through u is shorter.

  14. if(d[v]>d[u]+w[u][v]) {

    This line is a decision. if runs the block only when the condition is true.

  15. void path(int v) {

    This line defines a function. path stores the route found.

  16. if(p[v]==0) {

    This line is a decision. if runs the block only when the condition is true.

  17. printf("%d",v);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  18. return;

    This line returns from the function. return exits the function and hands back a value.

  19. path(p[v]);

    path stores the route found.

  20. printf(" -> %d",v);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  21. int main() {

    This line defines a function. main() is where the program starts running.

  22. int i,j,u,v,s,q_size,step=0;

    Declares the variables used below. q_size is how many items are in the queue. step counts the operations or stages printed in the trace.

  23. printf("Enter the number of vertices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  24. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  25. printf("Enter the %dx%d weight matrix (0 for no edge):\n",n,n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  26. for(u=1;u<=n;u++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  27. for(v=1;v<=n;v++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  28. scanf("%d",&w[u][v]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  29. printf("Enter the source vertex:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  30. scanf("%d",&s);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  31. int order[n+1],pos[n+1],trace[n+1][n+1];

    Declares the variables used below. order stores the sequence in which nodes are visited. n is the number of elements (or processes).

  32. char cell[12];

    Declares the variables used below. cell is one entry of the DP table.

  33. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  34. initialize_single_source(s);

    initialize_single_source() sets every distance to ∞ and the source to 0.

  35. q_size=n;

    q_size is how many items are in the queue. n is the number of elements (or processes).

  36. while(q_size!=0) {

    This line is a while loop. while (condition) repeats as long as the condition is true. q_size is how many items are in the queue.

  37. u=extract_min();

    extract_min() removes the node with the smallest key.

  38. q_size--;

    q_size is how many items are in the queue.

  39. step++;

    Counts one more basic operation. step counts the operations or stages printed in the trace.

  40. order[step]=u;

    order stores the sequence in which nodes are visited. step counts the operations or stages printed in the trace.

  41. pos[u]=step;

    pos is the current position. step counts the operations or stages printed in the trace.

  42. trace[step][v]=d[v];

    trace prints each step so you can follow the algorithm. step counts the operations or stages printed in the trace.

  43. if(w[u][v]!=0)

    This line is a decision. if runs the block only when the condition is true.

  44. relax(u,v);

    relax() updates dist[v] if going through u is shorter.

  45. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  46. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  47. printf("\nS = { }");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  48. printf("\nS = {%d}  (source, d[%d] = 0)\n",s,s);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  49. printf("\nu     ");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  50. if(v!=s)

    This line is a decision. if runs the block only when the condition is true.

  51. printf("%-6d",v);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  52. printf("S");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  53. for(i=2;i<=step;i++) {

    This line is the loop header. Counts one more basic operation. for (init; condition; update) repeats a block a counted number of times.

  54. if(trace[i][order[i]]==INF)

    This line is a decision. if runs the block only when the condition is true. trace prints each step so you can follow the algorithm.

  55. break;

    break leaves the nearest loop (or switch) immediately.

  56. printf("\n%-6d",order[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). order stores the sequence in which nodes are visited.

  57. if(v==s)

    This line is a decision. if runs the block only when the condition is true.

  58. continue;

    continue skips to the next loop iteration.

  59. if(trace[i][v]==INF)

    This line is a decision. if runs the block only when the condition is true. trace prints each step so you can follow the algorithm.

  60. printf("%-6s","INF");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  61. else if(pos[v]<=i) {

    This line is a decision. else runs when the if condition was false. if runs the block only when the condition is true.

  62. sprintf(cell,"(%d)",trace[i][v]);

    sprintf() formats text into a string instead of printing it. cell is one entry of the DP table. trace prints each step so you can follow the algorithm.

  63. printf("%-6s",cell);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). cell is one entry of the DP table.

  64. printf("%-6d",trace[i][v]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). trace prints each step so you can follow the algorithm.

  65. printf("{");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  66. for(j=1;j<=i;j++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  67. printf(j==1?"%d":", %d",order[j]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). order stores the sequence in which nodes are visited.

  68. printf("}");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  69. printf("\n( ) = vertex is in S, its shortest distance is final");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  70. printf("\n\nVertex\tDistance\tPath");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  71. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  72. if(d[i]==INF)

    This line is a decision. if runs the block only when the condition is true. INF stands for 'no edge / unreachable' (a very large number).

  73. printf("\n%d\tunreachable",i);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  74. else {

    This line is a decision. else runs when the if condition was false.

  75. printf("\n%d\t%d\t\t",i,d[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  76. path(i);

    path stores the route found.

  77. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  78. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  79. printf("\nTime complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  80. printf("\nSpace complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  81. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  82. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Dijkstra?

A. Best O(V²), average O(V²), worst O(V²). Design paradigm: Greedy.

Q. Dijkstra fails when the graph has…

A. Negative edge weights. Use Bellman–Ford for negative weights.

Q. RELAX(u, v) does…

A. if d[v] > d[u] + w(u, v): update d[v] and p[v]. Each vertex is finalised when it is extracted with the minimum d.

Q. With a binary heap, Dijkstra becomes…

A. O((V + E) log V). This program uses a matrix scan, so it is O(V²).

Program 24

Floyd–Warshall

Write a program in c to find the shortest paths between all pairs of vertices using the Floyd-Warshall algorithm and find its execution time using the time function.

Run it

Algorithm

Algorithm: FLOYD-WARSHALL(W)

1. Start
2. n <- number of vertices
3. For i <- 1 to n do
4.        For j <- 1 to n do
5.              if i == j then D[i][j] <- 0
6.              else if there is an edge (i,j) then D[i][j] <- W[i][j]
7.              else D[i][j] <- infinity
8. For k <- 1 to n do
9.        For i <- 1 to n do
10.             For j <- 1 to n do
11.                   if D[i][k] + D[k][j] < D[i][j] then
12.                         D[i][j] <- D[i][k] + D[k][j]
13. Print D
14. Stop

Program

#include<stdio.h>
#include<time.h>
#define INF 99999

int main() {
    int n,i,j,k,count=0;
    printf("Enter the number of vertices:");
    scanf("%d",&n);
    int D[n+1][n+1];
    printf("Enter the %dx%d weight matrix (0 for no edge):\n",n,n);
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
            scanf("%d",&D[i][j]);

    clock_t start=clock();
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
            if(i!=j && D[i][j]==0)
                D[i][j]=INF;
    for(k=1;k<=n;k++)
        for(i=1;i<=n;i++)
            for(j=1;j<=n;j++) {
                count++;
                if(D[i][k]!=INF && D[k][j]!=INF && D[i][k]+D[k][j]<D[i][j])
                    D[i][j]=D[i][k]+D[k][j];
            }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    printf("\nShortest distance matrix:\n");
    for(j=1;j<=n;j++)
        printf("\t%d",j);
    for(i=1;i<=n;i++) {
        printf("\n%d",i);
        for(j=1;j<=n;j++)
            if(D[i][j]==INF)
                printf("\tINF");
            else
                printf("\t%d",D[i][j]);
    }
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(V^3)");
    printf("\nSpace complexity: O(V^2)");
    printf("\n");
    return 0;
}

Output

Input typed: 4 ⏎ 0 3 0 7 ⏎ 8 0 2 0 ⏎ 5 0 0 1 ⏎ 2 0 0 0

Enter the number of vertices:4
Enter the 4x4 weight matrix (0 for no edge):
0 3 0 7
8 0 2 0
5 0 0 1
2 0 0 0

Shortest distance matrix:
	1	2	3	4
1	0	3	5	6
2	5	0	2	3
3	3	6	0	1
4	2	5	7	0
Number of comparisons:64
Time taken:0.000006 seconds
Time complexity: O(V^3)
Space complexity: O(V^2)

Complexity

Time complexity: O(V^3)
Space complexity: O(V^2)
Best caseO(V³)
Average caseO(V³)
Worst caseO(V³)
ParadigmDynamic programming

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. #define INF 99999

    INF stands for 'no edge / unreachable' (a very large number).

  2. int main() {

    This line defines a function. main() is where the program starts running.

  3. int n,i,j,k,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  4. printf("Enter the number of vertices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  5. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  6. int D[n+1][n+1];

    Declares the variables used below. n is the number of elements (or processes).

  7. printf("Enter the %dx%d weight matrix (0 for no edge):\n",n,n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  10. scanf("%d",&D[i][j]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  11. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  12. if(i!=j && D[i][j]==0)

    This line is a decision. if runs the block only when the condition is true.

  13. D[i][j]=INF;

    i is the loop counter. INF stands for 'no edge / unreachable' (a very large number).

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  15. for(j=1;j<=n;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  16. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  17. if(D[i][k]!=INF && D[k][j]!=INF && D[i][k]+D[k][j]<D[i][j])

    This line is a decision. if runs the block only when the condition is true. INF stands for 'no edge / unreachable' (a very large number).

  18. D[i][j]=D[i][k]+D[k][j];

    i is the loop counter.

  19. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  20. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  21. printf("\nShortest distance matrix:\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  22. printf("\t%d",j);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  23. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  24. printf("\n%d",i);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  25. if(D[i][j]==INF)

    This line is a decision. if runs the block only when the condition is true. INF stands for 'no edge / unreachable' (a very large number).

  26. printf("\tINF");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  27. printf("\t%d",D[i][j]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  28. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  29. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  30. printf("\nTime complexity: O(V^3)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  31. printf("\nSpace complexity: O(V^2)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  32. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  33. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Floyd–Warshall?

A. Best O(V³), average O(V³), worst O(V³). Design paradigm: Dynamic programming.

Q. Floyd–Warshall's update is…

A. d[i][j] = min(d[i][j], d[i][k] + d[k][j]). k is the outermost loop: allow vertex k as an intermediate.

Q. Floyd–Warshall solves…

A. All-pairs shortest paths. It handles negative edges, but not negative cycles.

Program 25

Bellman–Ford

Write a program in c to find the shortest path from a source vertex to all other vertices using the Bellman-Ford algorithm and find its execution time using the time function.

Run it

Algorithm

Algorithm: BELLMAN-FORD(G, w, s)

1. Start
2. For each vertex v in G do
3.        d[v] <- infinity
4.        p[v] <- NIL
5. d[s] <- 0
6. For i <- 1 to n-1 do
7.        For each edge (u,v) in G do
8.              if d[u] + w(u,v) < d[v] then
9.                    d[v] <- d[u] + w(u,v)
10.                   p[v] <- u
11. For each edge (u,v) in G do
12.       if d[u] + w(u,v) < d[v] then
13.             print "Graph contains a negative weight cycle"
14.             Stop
15. Print d[v] and the path to every vertex v using p
16. Stop

Program

#include<stdio.h>
#include<time.h>
#define INF 99999

int p[50];

void path(int v) {
    if(p[v]==0) {
        printf("%d",v);
        return;
    }
    path(p[v]);
    printf(" -> %d",v);
}

int main() {
    int n,e,i,j,s,neg=0,count=0;
    printf("Enter the number of vertices:");
    scanf("%d",&n);
    printf("Enter the number of edges:");
    scanf("%d",&e);
    int u[e],v[e],w[e],d[n+1];
    printf("Enter the edges (source destination weight):\n");
    for(j=0;j<e;j++)
        scanf("%d%d%d",&u[j],&v[j],&w[j]);
    printf("Enter the source vertex:");
    scanf("%d",&s);

    clock_t start=clock();
    for(i=1;i<=n;i++) {
        d[i]=INF;
        p[i]=0;
    }
    d[s]=0;
    for(i=1;i<=n-1;i++)
        for(j=0;j<e;j++) {
            count++;
            if(d[u[j]]!=INF && d[u[j]]+w[j]<d[v[j]]) {
                d[v[j]]=d[u[j]]+w[j];
                p[v[j]]=u[j];
            }
        }
    for(j=0;j<e;j++) {
        count++;
        if(d[u[j]]!=INF && d[u[j]]+w[j]<d[v[j]]) {
            neg=1;
            break;
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    if(neg)
        printf("\nGraph contains a negative weight cycle");
    else {
        printf("\nVertex\tDistance\tPath");
        for(i=1;i<=n;i++) {
            if(d[i]==INF)
                printf("\n%d\tunreachable",i);
            else {
                printf("\n%d\t%d\t\t",i,d[i]);
                path(i);
            }
        }
    }
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(VE)");
    printf("\nSpace complexity: O(V+E)");
    printf("\n");
    return 0;
}

Output

Input typed: 5 ⏎ 10 ⏎ 1 2 6 ⏎ 1 4 7 ⏎ 2 3 5 ⏎ 2 4 8 ⏎ 2 5 -4 ⏎ 3 2 -2 ⏎ 4 3 -3 ⏎ 4 5 9 ⏎ 5 1 2 ⏎ 5 3 7 ⏎ 1

Enter the number of vertices:5
Enter the number of edges:10
Enter the edges (source destination weight):
1 2 6
1 4 7
2 3 5
2 4 8
2 5 -4
3 2 -2
4 3 -3
4 5 9
5 1 2
5 3 7
Enter the source vertex:1

Vertex	Distance	Path
1	0		1
2	2		1 -> 4 -> 3 -> 2
3	4		1 -> 4 -> 3
4	7		1 -> 4
5	-2		1 -> 4 -> 3 -> 2 -> 5
Number of comparisons:50
Time taken:0.000009 seconds
Time complexity: O(VE)
Space complexity: O(V+E)

Complexity

Time complexity: O(VE)
Space complexity: O(V+E)
Best caseO(VE)
Average caseO(VE)
Worst caseO(VE)
ParadigmDynamic programming

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. #define INF 99999

    INF stands for 'no edge / unreachable' (a very large number).

  2. int p[50];

    Declares the variables used below.

  3. void path(int v) {

    This line defines a function. path stores the route found.

  4. if(p[v]==0) {

    This line is a decision. if runs the block only when the condition is true.

  5. printf("%d",v);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  6. return;

    This line returns from the function. return exits the function and hands back a value.

  7. path(p[v]);

    path stores the route found.

  8. printf(" -> %d",v);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  9. int main() {

    This line defines a function. main() is where the program starts running.

  10. int n,e,i,j,s,neg=0,count=0;

    Declares the variables used below. n is the number of elements (or processes). neg flags a negative cycle (Bellman–Ford).

  11. printf("Enter the number of vertices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  12. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  13. printf("Enter the number of edges:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  14. scanf("%d",&e);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  15. int u[e],v[e],w[e],d[n+1];

    Declares the variables used below. n is the number of elements (or processes).

  16. printf("Enter the edges (source destination weight):\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  17. for(j=0;j<e;j++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  18. scanf("%d%d%d",&u[j],&v[j],&w[j]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  19. printf("Enter the source vertex:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  20. scanf("%d",&s);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  21. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  22. for(i=1;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  23. d[i]=INF;

    i is the loop counter. INF stands for 'no edge / unreachable' (a very large number).

  24. p[i]=0;

    i is the loop counter.

  25. for(i=1;i<=n-1;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  26. for(j=0;j<e;j++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  27. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  28. if(d[u[j]]!=INF && d[u[j]]+w[j]<d[v[j]]) {

    This line is a decision. if runs the block only when the condition is true. INF stands for 'no edge / unreachable' (a very large number).

  29. d[v[j]]=d[u[j]]+w[j];

    j is the inner loop counter.

  30. p[v[j]]=u[j];

    j is the inner loop counter.

  31. neg=1;

    neg flags a negative cycle (Bellman–Ford).

  32. break;

    break leaves the nearest loop (or switch) immediately.

  33. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  34. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  35. if(neg)

    This line is a decision. if runs the block only when the condition is true. neg flags a negative cycle (Bellman–Ford).

  36. printf("\nGraph contains a negative weight cycle");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  37. else {

    This line is a decision. else runs when the if condition was false.

  38. printf("\nVertex\tDistance\tPath");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  39. if(d[i]==INF)

    This line is a decision. if runs the block only when the condition is true. INF stands for 'no edge / unreachable' (a very large number).

  40. printf("\n%d\tunreachable",i);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  41. printf("\n%d\t%d\t\t",i,d[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  42. path(i);

    path stores the route found.

  43. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  44. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  45. printf("\nTime complexity: O(VE)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  46. printf("\nSpace complexity: O(V+E)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  47. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  48. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Bellman–Ford?

A. Best O(VE), average O(VE), worst O(VE). Design paradigm: Dynamic programming.

Q. Bellman–Ford relaxes every edge how many times?

A. V − 1. A shortest path has at most V − 1 edges.

Q. How does it detect a negative cycle?

A. If any edge can still be relaxed after V − 1 rounds. That V-th round check is the negative-cycle test.

Program 26

Prim's MST

Write a program in c to find the minimum cost spanning tree of a graph using Prim's algorithm and find its execution time using the time function.

Run it

Algorithm

Algorithm: MST-PRIM(G, w, r)

1. for each u in V[G]
2.       do key[u] <- infinity
3.          p[u] <- NIL
4. key[r] <- 0
5. Q <- V[G]
6. while Q != Ø
7.       do u <- EXTRACT-MIN(Q)
8.          for each v in Adj[u]
9.                do if v in Q and w(u,v) < key[v]
10.                     then p[v] <- u
11.                          key[v] <- w(u,v)

EXTRACT-MIN(Q)
1. u <- the vertex in Q with minimum key[u]
2. Q <- Q - {u}
3. return u

Program

#include<stdio.h>
#include<time.h>
#define INF 99999

int n,count=0;
int w[50][50],key[50],p[50],Q[50];

int extract_min() {
    int v,u=0;
    for(v=1;v<=n;v++) {
        count++;
        if(Q[v]==1 && (u==0 || key[v]<key[u]))
            u=v;
    }
    Q[u]=0;
    return u;
}

int main() {
    int i,u,v,r,q_size,step=0,cost=0;
    printf("Enter the number of vertices:");
    scanf("%d",&n);
    printf("Enter the %dx%d weight matrix (0 for no edge):\n",n,n);
    for(u=1;u<=n;u++)
        for(v=1;v<=n;v++)
            scanf("%d",&w[u][v]);
    printf("Enter the root vertex:");
    scanf("%d",&r);

    int order[n+1];

    clock_t start=clock();
    for(u=1;u<=n;u++) {
        key[u]=INF;
        p[u]=0;
    }
    key[r]=0;
    for(u=1;u<=n;u++)
        Q[u]=1;
    q_size=n;
    while(q_size!=0) {
        u=extract_min();
        q_size--;
        if(key[u]==INF)
            break;
        step++;
        order[step]=u;
        for(v=1;v<=n;v++)
            if(w[u][v]!=0) {
                count++;
                if(Q[v]==1 && w[u][v]<key[v]) {
                    p[v]=u;
                    key[v]=w[u][v];
                }
            }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    if(step<n)
        printf("\nGraph is disconnected, no spanning tree exists");
    else {
        printf("\nEdges in the minimum spanning tree (in the order added):");
        printf("\nEdge\t\tWeight");
        for(i=2;i<=n;i++) {
            v=order[i];
            printf("\n%d - %d\t\t%d",p[v],v,key[v]);
            cost+=key[v];
        }
        printf("\nMinimum cost of spanning tree:%d",cost);
    }
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list and binary heap");
    printf("\nSpace complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list");
    printf("\n");
    return 0;
}

Output

Input typed: 9 ⏎ 0 4 0 0 0 0 0 8 0 ⏎ 4 0 8 0 0 0 0 11 0 ⏎ 0 8 0 7 0 4 0 0 2 ⏎ 0 0 7 0 9 14 0 0 0 ⏎ 0 0 0 9 0 10 0 0 0 ⏎ 0 0 4 14 10 0 2 0 0 ⏎ 0 0 0 0 0 2 0 1 6 ⏎ 8 11 0 0 0 0 1 0 7 ⏎ 0 0 2 0 0 0 6 7 0 ⏎ 1

Enter the number of vertices:9
Enter the 9x9 weight matrix (0 for no edge):
0 4 0 0 0 0 0 8 0
4 0 8 0 0 0 0 11 0
0 8 0 7 0 4 0 0 2
0 0 7 0 9 14 0 0 0
0 0 0 9 0 10 0 0 0
0 0 4 14 10 0 2 0 0
0 0 0 0 0 2 0 1 6
8 11 0 0 0 0 1 0 7
0 0 2 0 0 0 6 7 0
Enter the root vertex:1

Edges in the minimum spanning tree (in the order added):
Edge		Weight
1 - 2		4
2 - 3		8
3 - 9		2
3 - 6		4
6 - 7		2
7 - 8		1
3 - 4		7
4 - 5		9
Minimum cost of spanning tree:37
Number of comparisons:109
Time taken:0.000005 seconds
Time complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list and binary heap
Space complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list

Complexity

Time complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list and binary heap
Space complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list
Best caseO(V²)
Average caseO(V²)
Worst caseO(V²)
ParadigmGreedy

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. #define INF 99999

    INF stands for 'no edge / unreachable' (a very large number).

  2. int n,count=0;

    Declares the variables used below. n is the number of elements (or processes). count tallies the basic operations (comparisons/steps) to show the complexity.

  3. int w[50][50],key[50],p[50],Q[50];

    Declares the variables used below. key is the value being searched for, or the element being inserted.

  4. int extract_min() {

    This line defines a function. extract_min() removes the node with the smallest key.

  5. int v,u=0;

    Declares the variables used below.

  6. for(v=1;v<=n;v++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  7. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  8. if(Q[v]==1 && (u==0 || key[v]<key[u]))

    This line is a decision. if runs the block only when the condition is true. key is the value being searched for, or the element being inserted.

  9. return u;

    This line returns from the function. return exits the function and hands back a value.

  10. int main() {

    This line defines a function. main() is where the program starts running.

  11. int i,u,v,r,q_size,step=0,cost=0;

    Declares the variables used below. q_size is how many items are in the queue. step counts the operations or stages printed in the trace.

  12. printf("Enter the number of vertices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  13. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  14. printf("Enter the %dx%d weight matrix (0 for no edge):\n",n,n);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). n is the number of elements (or processes).

  15. for(u=1;u<=n;u++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  16. for(v=1;v<=n;v++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  17. scanf("%d",&w[u][v]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  18. printf("Enter the root vertex:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  19. scanf("%d",&r);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  20. int order[n+1];

    Declares the variables used below. order stores the sequence in which nodes are visited. n is the number of elements (or processes).

  21. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

  22. for(u=1;u<=n;u++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  23. key[u]=INF;

    key is the value being searched for, or the element being inserted. INF stands for 'no edge / unreachable' (a very large number).

  24. key[r]=0;

    key is the value being searched for, or the element being inserted.

  25. q_size=n;

    q_size is how many items are in the queue. n is the number of elements (or processes).

  26. while(q_size!=0) {

    This line is a while loop. while (condition) repeats as long as the condition is true. q_size is how many items are in the queue.

  27. u=extract_min();

    extract_min() removes the node with the smallest key.

  28. q_size--;

    q_size is how many items are in the queue.

  29. if(key[u]==INF)

    This line is a decision. if runs the block only when the condition is true. key is the value being searched for, or the element being inserted.

  30. break;

    break leaves the nearest loop (or switch) immediately.

  31. step++;

    Counts one more basic operation. step counts the operations or stages printed in the trace.

  32. order[step]=u;

    order stores the sequence in which nodes are visited. step counts the operations or stages printed in the trace.

  33. if(w[u][v]!=0) {

    This line is a decision. if runs the block only when the condition is true.

  34. if(Q[v]==1 && w[u][v]<key[v]) {

    This line is a decision. if runs the block only when the condition is true. key is the value being searched for, or the element being inserted.

  35. key[v]=w[u][v];

    key is the value being searched for, or the element being inserted.

  36. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  37. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  38. if(step<n)

    This line is a decision. if runs the block only when the condition is true. step counts the operations or stages printed in the trace.

  39. printf("\nGraph is disconnected, no spanning tree exists");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  40. else {

    This line is a decision. else runs when the if condition was false.

  41. printf("\nEdges in the minimum spanning tree (in the order added):");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  42. printf("\nEdge\t\tWeight");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  43. for(i=2;i<=n;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  44. v=order[i];

    order stores the sequence in which nodes are visited.

  45. printf("\n%d - %d\t\t%d",p[v],v,key[v]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). key is the value being searched for, or the element being inserted.

  46. cost+=key[v];

    cost holds the edge weights (the adjacency/cost matrix). key is the value being searched for, or the element being inserted.

  47. printf("\nMinimum cost of spanning tree:%d",cost);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). cost holds the edge weights (the adjacency/cost matrix).

  48. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  49. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  50. printf("\nTime complexity: O(V^2) with adjacency matrix, O(E log V) with adjacency list and binary heap");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  51. printf("\nSpace complexity: O(V^2) with adjacency matrix, O(V+E) with adjacency list");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  52. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  53. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Prim's MST?

A. Best O(V²), average O(V²), worst O(V²). Design paradigm: Greedy.

Q. Prim's algorithm grows the MST by…

A. Adding the cheapest edge from the tree to a new vertex. Kruskal is the one that picks the globally cheapest edge.

Q. A spanning tree on V vertices has how many edges?

A. V − 1. Connected and without cycles.

Program 27

Kruskal's MST

Write a program in c to find the minimum cost spanning tree of a graph using Kruskal's algorithm and find its execution time using the time function.

Run it

Algorithm

Algorithm: MST-KRUSKAL(G, w)

1. A <- Ø
2. for each vertex v in V[G]
3.       do MAKE-SET(v)
4. sort the edges of E into nondecreasing order by weight w
5. for each edge (u,v) in E, taken in nondecreasing order by weight
6.       do if FIND-SET(u) != FIND-SET(v)
7.             then A <- A U {(u,v)}
8.                  UNION(u,v)
9. return A

MAKE-SET(x)
1. parent[x] <- x
2. rank[x] <- 0

FIND-SET(x)
1. if x != parent[x]
2.       then parent[x] <- FIND-SET(parent[x])
3. return parent[x]

UNION(x, y)
1. x <- FIND-SET(x), y <- FIND-SET(y)
2. if rank[x] > rank[y]
3.       then parent[y] <- x
4.       else parent[x] <- y
5.            if rank[x] == rank[y]
6.                  then rank[y] <- rank[y] + 1

Program

#include<stdio.h>
#include<time.h>

int parent[50],rnk[50];

void make_set(int x) {
    parent[x]=x;
    rnk[x]=0;
}

int find_set(int x) {
    if(x!=parent[x])
        parent[x]=find_set(parent[x]);
    return parent[x];
}

void union_set(int x,int y) {
    x=find_set(x);
    y=find_set(y);
    if(rnk[x]>rnk[y])
        parent[y]=x;
    else {
        parent[x]=y;
        if(rnk[x]==rnk[y])
            rnk[y]++;
    }
}

int main() {
    int n,e,i,j,k=0,cost=0,count=0,tu,tv,tw;
    printf("Enter the number of vertices:");
    scanf("%d",&n);
    printf("Enter the number of edges:");
    scanf("%d",&e);
    int u[e],v[e],w[e],au[n],av[n],aw[n];
    printf("Enter the edges (vertex vertex weight):\n");
    for(i=0;i<e;i++)
        scanf("%d%d%d",&u[i],&v[i],&w[i]);

    clock_t start=clock();
    for(i=1;i<=n;i++)
        make_set(i);
    for(i=1;i<e;i++) {
        tu=u[i];
        tv=v[i];
        tw=w[i];
        j=i-1;
        while(j>=0) {
            count++;
            if(w[j]<=tw)
                break;
            u[j+1]=u[j];
            v[j+1]=v[j];
            w[j+1]=w[j];
            j--;
        }
        u[j+1]=tu;
        v[j+1]=tv;
        w[j+1]=tw;
    }
    for(i=0;i<e && k<n-1;i++) {
        count++;
        if(find_set(u[i])!=find_set(v[i])) {
            au[k]=u[i];
            av[k]=v[i];
            aw[k]=w[i];
            k++;
            union_set(u[i],v[i]);
        }
    }
    clock_t end=clock();
    double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    if(k<n-1)
        printf("\nGraph is disconnected, no spanning tree exists");
    else {
        printf("\nEdges in the minimum spanning tree (in the order added):");
        printf("\nEdge\t\tWeight");
        for(i=0;i<k;i++) {
            printf("\n%d - %d\t\t%d",au[i],av[i],aw[i]);
            cost+=aw[i];
        }
        printf("\nMinimum cost of spanning tree:%d",cost);
    }
    printf("\nNumber of comparisons:%d",count);
    printf("\nTime taken:%f seconds",time_taken);
    printf("\nTime complexity: O(E log E) with merge sort, O(E^2) with the insertion sort used here");
    printf("\nSpace complexity: O(V+E)");
    printf("\n");
    return 0;
}

Output

Input typed: 9 ⏎ 14 ⏎ 1 2 4 ⏎ 1 8 8 ⏎ 2 3 8 ⏎ 2 8 11 ⏎ 3 4 7 ⏎ 3 6 4 ⏎ 3 9 2 ⏎ 4 5 9 ⏎ 4 6 14 ⏎ 5 6 10 ⏎ 6 7 2 ⏎ 7 8 1 ⏎ 7 9 6 ⏎ 8 9 7

Enter the number of vertices:9
Enter the number of edges:14
Enter the edges (vertex vertex weight):
1 2 4
1 8 8
2 3 8
2 8 11
3 4 7
3 6 4
3 9 2
4 5 9
4 6 14
5 6 10
6 7 2
7 8 1
7 9 6
8 9 7

Edges in the minimum spanning tree (in the order added):
Edge		Weight
7 - 8		1
3 - 9		2
6 - 7		2
1 - 2		4
3 - 6		4
3 - 4		7
1 - 8		8
4 - 5		9
Minimum cost of spanning tree:37
Number of comparisons:71
Time taken:0.000010 seconds
Time complexity: O(E log E) with merge sort, O(E^2) with the insertion sort used here
Space complexity: O(V+E)

Complexity

Time complexity: O(E log E) with merge sort, O(E^2) with the insertion sort used here
Space complexity: O(V+E)
Best caseO(E²)
Average caseO(E²)
Worst caseO(E²)
ParadigmGreedy

Viva: which header is used and why

Q. Why #include <stdio.h>?

A. stdio.h is standard input/output: printf, scanf. Used here for: printf, scanf.

Q. Why #include <time.h>?

A. time.h: clock(), clock_t, CLOCKS_PER_SEC for timing. Used here for: clock, clock_t, CLOCKS_PER_SEC.

Viva: what does each line do?

  1. int parent[50],rnk[50];

    Declares the variables used below. parent records each node's predecessor, used to rebuild the tree or path. rnk (rank) keeps union–find trees shallow.

  2. void make_set(int x) {

    This line defines a function. make_set() starts each vertex in its own set (union–find).

  3. parent[x]=x;

    parent records each node's predecessor, used to rebuild the tree or path.

  4. rnk[x]=0;

    rnk (rank) keeps union–find trees shallow.

  5. int find_set(int x) {

    This line defines a function. find_set() returns the set representative, which is how Kruskal detects cycles.

  6. if(x!=parent[x])

    This line is a decision. if runs the block only when the condition is true. parent records each node's predecessor, used to rebuild the tree or path.

  7. parent[x]=find_set(parent[x]);

    parent records each node's predecessor, used to rebuild the tree or path. find_set() returns the set representative, which is how Kruskal detects cycles.

  8. return parent[x];

    This line returns from the function. return exits the function and hands back a value. parent records each node's predecessor, used to rebuild the tree or path.

  9. void union_set(int x,int y) {

    This line defines a function. union_set() merges two sets after an edge is accepted.

  10. x=find_set(x);

    find_set() returns the set representative, which is how Kruskal detects cycles.

  11. y=find_set(y);

    find_set() returns the set representative, which is how Kruskal detects cycles.

  12. if(rnk[x]>rnk[y])

    This line is a decision. if runs the block only when the condition is true. rnk (rank) keeps union–find trees shallow.

  13. parent[y]=x;

    parent records each node's predecessor, used to rebuild the tree or path.

  14. else {

    This line is a decision. else runs when the if condition was false.

  15. parent[x]=y;

    parent records each node's predecessor, used to rebuild the tree or path.

  16. if(rnk[x]==rnk[y])

    This line is a decision. if runs the block only when the condition is true. rnk (rank) keeps union–find trees shallow.

  17. rnk[y]++;

    rnk (rank) keeps union–find trees shallow.

  18. int main() {

    This line defines a function. main() is where the program starts running.

  19. int n,e,i,j,k=0,cost=0,count=0,tu,tv,tw;

    Declares the variables used below. n is the number of elements (or processes). cost holds the edge weights (the adjacency/cost matrix).

  20. printf("Enter the number of vertices:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  21. scanf("%d",&n);

    This line reads input. scanf() reads input into variables; pass their addresses with &. n is the number of elements (or processes).

  22. printf("Enter the number of edges:");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  23. scanf("%d",&e);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  24. int u[e],v[e],w[e],au[n],av[n],aw[n];

    Declares the variables used below. n is the number of elements (or processes).

  25. printf("Enter the edges (vertex vertex weight):\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  26. for(i=0;i<e;i++)

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  27. scanf("%d%d%d",&u[i],&v[i],&w[i]);

    This line reads input. scanf() reads input into variables; pass their addresses with &.

  28. clock_t start=clock();

    This line records the time. clock_t is the type that holds clock() readings. start stores clock() before the algorithm runs.

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

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  30. make_set(i);

    make_set() starts each vertex in its own set (union–find).

  31. for(i=1;i<e;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  32. tu=u[i];

    i is the loop counter.

  33. tv=v[i];

    i is the loop counter.

  34. tw=w[i];

    i is the loop counter.

  35. j=i-1;

    j is the inner loop counter.

  36. while(j>=0) {

    This line is a while loop. while (condition) repeats as long as the condition is true.

  37. count++;

    Counts one more basic operation. count tallies the basic operations (comparisons/steps) to show the complexity.

  38. if(w[j]<=tw)

    This line is a decision. if runs the block only when the condition is true.

  39. break;

    break leaves the nearest loop (or switch) immediately.

  40. u[j+1]=u[j];

    j is the inner loop counter.

  41. v[j+1]=v[j];

    j is the inner loop counter.

  42. w[j+1]=w[j];

    j is the inner loop counter.

  43. j--;

    j is the inner loop counter.

  44. u[j+1]=tu;

    j is the inner loop counter.

  45. v[j+1]=tv;

    j is the inner loop counter.

  46. w[j+1]=tw;

    j is the inner loop counter.

  47. for(i=0;i<e && k<n-1;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times. n is the number of elements (or processes).

  48. if(find_set(u[i])!=find_set(v[i])) {

    This line is a decision. if runs the block only when the condition is true. find_set() returns the set representative, which is how Kruskal detects cycles.

  49. au[k]=u[i];

    i is the loop counter.

  50. av[k]=v[i];

    i is the loop counter.

  51. aw[k]=w[i];

    i is the loop counter.

  52. union_set(u[i],v[i]);

    union_set() merges two sets after an edge is accepted.

  53. clock_t end=clock();

    This line records the time. clock_t is the type that holds clock() readings. end stores clock() after the algorithm finishes.

  54. double time_taken=(double)(end-start)/CLOCKS_PER_SEC;

    time_taken = (end − start) / CLOCKS_PER_SEC, in seconds. end stores clock() after the algorithm finishes. start stores clock() before the algorithm runs.

  55. if(k<n-1)

    This line is a decision. if runs the block only when the condition is true. n is the number of elements (or processes).

  56. printf("\nGraph is disconnected, no spanning tree exists");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  57. printf("\nEdges in the minimum spanning tree (in the order added):");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  58. printf("\nEdge\t\tWeight");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  59. for(i=0;i<k;i++) {

    This line is the loop header. for (init; condition; update) repeats a block a counted number of times.

  60. printf("\n%d - %d\t\t%d",au[i],av[i],aw[i]);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  61. cost+=aw[i];

    cost holds the edge weights (the adjacency/cost matrix).

  62. printf("\nMinimum cost of spanning tree:%d",cost);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). cost holds the edge weights (the adjacency/cost matrix).

  63. printf("\nNumber of comparisons:%d",count);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). count tallies the basic operations (comparisons/steps) to show the complexity.

  64. printf("\nTime taken:%f seconds",time_taken);

    This line prints output. printf() prints formatted output (%d int, %f float, %s string). time_taken = (end − start) / CLOCKS_PER_SEC, in seconds.

  65. printf("\nTime complexity: O(E log E) with merge sort, O(E^2) with the insertion sort used here");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  66. printf("\nSpace complexity: O(V+E)");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  67. printf("\n");

    This line prints output. printf() prints formatted output (%d int, %f float, %s string).

  68. return 0;

    This line returns from the function. return exits the function and hands back a value.

Viva: concepts

Q. What is the time complexity of Kruskal's MST?

A. Best O(E²), average O(E²), worst O(E²). Design paradigm: Greedy.

Q. Kruskal adds edges in order of…

A. Increasing weight, skipping edges that form a cycle. Union-Find checks whether the two ends are already connected.

Q. Kruskal is better than Prim on…

A. Sparse graphs (few edges). It sorts E edges, so it is O(E log E) with a proper sort.

Theory: complexity classes

Asymptotic notations

  • Growth order: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(n³) < O(2ⁿ) < O(n!).
  • Best case = fewest steps for any input of size n; worst case = most steps; average case = expected steps over all inputs.
  • Space complexity = extra memory the algorithm needs (auxiliary space), not counting the input.
  • In the lab, time is measured with clock(): (end − start) / CLOCKS_PER_SEC gives seconds; 'count' tallies the basic operation.
NotationMeaningDefinition
Big-O O(g(n))Upper bound (at most)f(n) ≤ c·g(n) for all n ≥ n₀
Big-Omega Ω(g(n))Lower bound (at least)f(n) ≥ c·g(n) for all n ≥ n₀
Big-Theta Θ(g(n))Tight bound (exactly that order)c₁·g(n) ≤ f(n) ≤ c₂·g(n) for all n ≥ n₀
little-o o(g(n))Strictly smaller orderf(n)/g(n) → 0
little-omega ω(g(n))Strictly larger orderf(n)/g(n) → ∞

Recurrences and the Master theorem

  • Divide-and-conquer time is written as T(n) = a·T(n/b) + f(n): a subproblems of size n/b, plus f(n) to split and combine.
  • Compare f(n) with n^(log_b a):
  • Case 1: f(n) smaller → T(n) = Θ(n^(log_b a)).
  • Case 2: f(n) equal → T(n) = Θ(n^(log_b a) · log n).
  • Case 3: f(n) bigger (and regular) → T(n) = Θ(f(n)).
AlgorithmRecurrenceResult
Binary searchT(n) = T(n/2) + O(1)O(log n)
Merge sortT(n) = 2T(n/2) + O(n)O(n log n)
Quick sort (best/avg)T(n) = 2T(n/2) + O(n)O(n log n)
Quick sort (worst)T(n) = T(n − 1) + O(n)O(n²)
Recursive FibonacciT(n) = T(n − 1) + T(n − 2) + O(1)O(2ⁿ)

Complexity classes: P, NP, NP-complete, NP-hard

  • Decision problem: the answer is yes/no (e.g. 'is there a tour of cost ≤ k?'). Optimisation problem: find the best value (e.g. 'shortest tour'). Classes P and NP are defined for decision problems.
  • P: problems solvable in polynomial time by a deterministic algorithm. Examples: sorting, searching, shortest path (Dijkstra), MST (Prim, Kruskal).
  • NP: problems whose 'yes' answer can be verified in polynomial time (equivalently, solvable in polynomial time by a non-deterministic algorithm). Every P problem is in NP, so P ⊆ NP.
  • NP-hard: every NP problem can be reduced to it in polynomial time. It may not be in NP itself (e.g. the optimisation version of TSP, the halting problem).
  • NP-complete: in NP and NP-hard at the same time, the hardest problems in NP. Examples: SAT, 3-SAT, vertex cover, clique, Hamiltonian cycle, TSP (decision), 0/1 knapsack (decision), subset sum, graph colouring.
  • Cook–Levin theorem: SAT was the first problem proved NP-complete.
  • Reduction (A ≤ₚ B): convert any instance of A to B in polynomial time. To prove X is NP-complete: show X ∈ NP, then reduce a known NP-complete problem to X.
  • Co-NP: problems whose 'no' answer can be verified in polynomial time.
  • P vs NP is unsolved: if any NP-complete problem has a polynomial algorithm, then P = NP.
  • Tractable = solvable in polynomial time; intractable = no known polynomial algorithm.
  • Non-deterministic algorithm: uses choice() to guess, then failure()/success() to check; it 'guesses' a solution and verifies it in polynomial time.
ClassSolve in poly time?Verify in poly time?Lab example
PYesYesBinary search, sorting, Dijkstra, Prim, Kruskal, BFS, DFS
NPNot knownYesSubset sum, 0/1 knapsack (decision), N-Queen existence
NP-completeNot knownYes0/1 knapsack (decision), TSP (decision), subset sum
NP-hardNot knownNot necessarilyTSP (optimisation, program 19 / 22)

Design paradigms in this lab

ParadigmIdeaLab programs
Brute forceTry every possibility directlyLinear search, bubble sort, selection sort
Divide & conquerSplit, solve parts recursively, combineBinary search, merge sort, quick sort
GreedyTake the best local choice each stepFractional knapsack, job sequencing, Huffman, Prim, Kruskal, Dijkstra
Dynamic programmingStore answers of overlapping subproblemsFibonacci DP, MCM, 0/1 knapsack, LCS, Floyd–Warshall, Bellman–Ford, TSP
BacktrackingBuild step by step, undo on a dead endN-Queen
Branch & boundExplore states, prune with boundsJob assignment

Theory viva

Q. What is an algorithm?

A. A finite sequence of well-defined steps that takes input and produces output. Properties: input, output, definiteness, finiteness, effectiveness.

Q. Why use asymptotic notation instead of seconds?

A. Seconds depend on the machine and compiler; asymptotic notation describes how the work grows with n, independent of hardware.

Q. Difference between O, Ω and Θ?

A. O is an upper bound, Ω a lower bound and Θ a tight bound (both at once).

Q. What is the difference between P and NP?

A. P problems can be solved in polynomial time; NP problems can have a proposed solution verified in polynomial time. P ⊆ NP; whether P = NP is unknown.

Q. What is the difference between NP-hard and NP-complete?

A. NP-complete problems are NP-hard AND in NP. NP-hard problems need not be in NP (they may not even be decision problems).

Q. Give an NP-complete problem.

A. SAT (the first, by Cook's theorem), 3-SAT, vertex cover, Hamiltonian cycle, subset sum, 0/1 knapsack (decision).

Q. Is 0/1 knapsack solved in polynomial time by DP?

A. No: O(nW) is pseudo-polynomial because it depends on the numeric value W, not the input size. The decision version is NP-complete.

Q. What is a reduction?

A. A polynomial-time conversion of one problem into another, used to show the second is at least as hard as the first.

Q. Greedy vs dynamic programming?

A. Greedy commits to the best local choice and never revisits it; DP solves all subproblems and combines them, so it works when greedy choice fails (e.g. 0/1 knapsack).

Q. Backtracking vs branch & bound?

A. Backtracking explores depth-first and undoes choices that break constraints; branch & bound uses cost bounds to prune and usually explores the least-cost node first.

Subject viva

Basics

Q. What is an algorithm? What are its properties?

A. A finite sequence of well-defined steps that solves a problem. Properties: input, output, definiteness, finiteness and effectiveness.

Analysis

Q. Big-O, Big-Ω and Big-Θ?

A. O is an upper bound (worst-case growth), Ω a lower bound, and Θ a tight bound (both). For example, merge sort is Θ(n log n).

Q. Best, average and worst case?

A. The minimum, expected and maximum running time over inputs of size n. For linear search: O(1), O(n), O(n).

Q. Time vs space complexity?

A. Time complexity counts the basic operations as a function of n. Space complexity counts the extra memory used. The two often trade off, e.g. DP tables use memory to save time.

Q. Why measure comparisons as well as clock() time?

A. clock() depends on the machine and is too coarse for tiny inputs. Operation counts are machine-independent and match the theoretical complexity directly.

Q. State the master theorem.

A. For T(n) = aT(n/b) + f(n), compare f(n) with n^(log_b a): if it is smaller, T = Θ(n^(log_b a)); if equal, T = Θ(n^(log_b a) · log n); if larger (with the regularity condition), T = Θ(f(n)).

Sorting

Q. Which sorts are stable and which are in-place?

A. Stable: bubble, insertion, merge, radix, counting. Not stable: selection, quick, heap. In-place: bubble, selection, insertion, quick, heap. Merge sort needs O(n) extra space.

Q. What is the lower bound for comparison sorting?

A. Ω(n log n), from the decision-tree argument (log₂ n! ≈ n log n). Radix and counting sort beat it by not comparing elements.

Paradigms

Q. Divide & conquer vs dynamic programming?

A. Both split a problem into subproblems. D&C subproblems are independent (merge sort). DP subproblems overlap, so their answers are stored and reused (Fibonacci, LCS).

Q. When does a greedy algorithm give the optimal answer?

A. When the problem has the greedy-choice property and optimal substructure: fractional knapsack, Huffman, Prim, Kruskal, Dijkstra. 0/1 knapsack fails with greedy.

Q. Backtracking vs branch & bound?

A. Backtracking explores the state space depth-first and abandons partial solutions that break constraints (N-Queen). Branch & bound uses cost bounds to prune and is used for optimisation (job assignment, TSP).

Q. Memoization vs tabulation?

A. Memoization is top-down recursion with a cache. Tabulation is bottom-up, filling a table iteratively. Both turn exponential recursion into polynomial time when subproblems overlap.

Graphs

Q. BFS vs DFS?

A. BFS uses a queue, explores level by level and finds the fewest-edge paths. DFS uses a stack or recursion, goes deep first, and is used for cycles, topological sort and components. Both are O(V+E) with adjacency lists.

Q. Dijkstra vs Bellman–Ford vs Floyd–Warshall?

A. Dijkstra: single source, no negative edges, O(V²) or O(E log V) (greedy). Bellman–Ford: single source, allows negative edges and detects negative cycles, O(VE) (DP). Floyd–Warshall: all pairs, O(V³) (DP).

Q. Prim vs Kruskal?

A. Both find an MST greedily. Prim grows one tree from a vertex (better for dense graphs, O(V²) with a matrix). Kruskal sorts the edges and joins components with Union-Find (better for sparse graphs, O(E log E)).

Complexity

Q. P, NP, NP-complete and NP-hard?

A. P: solvable in polynomial time. NP: a solution can be verified in polynomial time. NP-complete: in NP and as hard as every NP problem (SAT, 0/1 knapsack decision). NP-hard: at least as hard, but not necessarily in NP (TSP optimisation).

Q. Why is 0/1 knapsack's O(nW) not polynomial?

A. It is pseudo-polynomial: W is a numeric value, and the input only needs log W bits for it, so the running time is exponential in the input size.

Classic

Q. Why is the Huffman code optimal?

A. Merging the two least frequent symbols first always gives an optimal prefix-free code (greedy choice plus optimal substructure). It minimises Σ frequency × code length.