Daa Lab Manual2020 1
Daa Lab Manual2020 1
S J C INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Assistant Professor
Department of ISE
SJCIT, Chickballapur
S.J.C.INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
CHICKBALLAPUR -562101
Year 2020
Estd: 1986
Department of Information Science & Engineering
SEMESTER – IV
Description
Design, develop, and implement the specified algorithms for the following problems using
Java language under LINUX /Windows environment. Net beans/Eclipse IDE tool can be used
for development and demonstration.
LIST OF EXPERIEMENTS
1a) Create a Java Class Called Student with the following details as variables within it
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create n Student objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.
1b) Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display()
methods to demonstrate its working.
2a) Design a super class called Staff with details as Staff Id, Name, Phone, Salary. Extend this class
by writing three subclasses namely Teaching (domain, publications), Technical (skills), and
Contract (period). Write a Java program to read and display at least 3 staff objects of all three
categories.
2b) Write a Java class called Customer to store their name and date_of_birth. The date_of_birth
format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy>
and display as <name, dd, mm, yyyy> using StringTokenizer class considering the delimiter
character as “/”.
3a) Write a Java program to read two integers a and b. Compute a/b and print, when b is not
zero. Raise an exception when b is equal to zero.
3b) Write a Java program that implements a multi-thread application that has three threads. First
thread generates a random integer for every 1 second; second thread computes the square of
the number and prints; third thread will print the value of cube of the number.
4) Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to sort.
Plot a graph of the time taken versus non graph sheet. The elements can be read from a file or
can be generated using the random number generator. Demonstrate using Java how the divide-
and-conquer method works along with its time complexity analysis: worst case, average case
and best case.
5)Sort a given set of n integer elements using Merge Sort method and compute its time complexity.
Run the program for varied values of n> 5000, and record the time taken to sort. Plot a graph of
the time taken versus non graph sheet. The elements can be read from a file or can be generated
using the random number generator. Demonstrate using Java how the divide- and-conquer
method works along with its time complexity analysis: worst case, average case and best case.
6) Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method
(b) Greedy method.
7) From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijkstra's algorithm. Write the program in Java.
9) Find Minimum Cost Spanning Tree of a given connected undirected graph using
Prim's algorithm
11) Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n positive
integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6,
8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the
given problem instance doesn't have a solution.
12) Design and implement in Java to find all Hamiltonian Cycles in a connected
undirected Graph G of n vertices using backtracking principle.
COURSE OUTCOMES
EXPERIMENT 1A
PROGRAM STATEMENT
Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create n Student objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.
CONCEPT
In Java everything is encapsulated under classes. Class is the core of Java language. Class can
be defined as a template/ blueprint that describe the behaviors /states of a particular entity. A
class defines new data type. This type can be used to create object of that type. Object is an
instance of class. You may also call it as physical existence of a logical template class.
A class is declared using class keyword. A class contains both data and code that operate on
that data. The data or variables defined within a class are called instance variables and the code
that operates on this data is known as methods.
A simple class example
class Student
{
String USN,name , branch;
int phoneno;
}
Object is an instance of a class created using a new operator. The new operator returns a reference
to a new instance of a class. This reference can be assigned to a reference variable of the class.
The process of creating objects from a class is called instantiation. An object encapsulates state and
behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java,
objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such
as integer or float. Each time you create an object, a new set of instance variables comes into
existence which defines the characteristics of that object. If you want to create an object of the
class and have the reference variable associated with this object, you must also allocate memory
for the object by using the new operator . This process is called instantiating an object or
creating an object instance. In following statement obj is instance/object of Student class.
An array of objects is created just like an array of primitive type data items in the following
way.
Student[] obj_Array = new Student[7];
However, in this particular case, we may use a for loop since all Student objects are created
with the same default constructor.
Constructor in java is a special type of method that is used to initialize the object. Java
constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Object creation:
Student obj=new Student();
Constructor with arguments is known as parameterized constructor.
Student(int i,String n)
{
id = i;
name = n;
}
Object creation:
Student4 s1 = new Student4(111,"Karan");
PROGRAM
/* 1a. Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create nStudent objects and print the USN, Name, Branch, and Phone
of these objects with suitable headings.
*/
import java.util.Scanner;
class Student
{
void read()
{
System.out.println("Enter Student Details");
System.out.println("Enter USN");
USN = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Branch");
Branch = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
}
void display()
{
System.out.printf("%-20s %-20s %-20s %-20s", USN, Name, Branch, Phone);
}
}
class studentdetails
{
}
input.close();
}
}
1sj15me45
Enter Name
harish
Enter Branch
med
Enter Phone
984512345
Enter Student Details
Enter USN
1sj17ec111
Enter Name
shalini
Enter Branch
ece
Enter Phone
9982345678
USN NAME BRANCH PHONE
1sj16cs097 ramu cse 992345678
1sj15me45 harish med 984512345
1sj17ec111 shalini ece 9982345678
EXPERIMENT 1B
PROGRAM STATEMENT
Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display()
methods to demonstrate its working
CONCEPT
In Java everything is encapsulated under classes. Class is the core of Java language. Class can be
defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class
defines new data type. This type can be used to create object of that type. Object is an instance of
class. You may also call it as physical existence of a logical template class. A class is declared using
class keyword. A class contains both data and code that operate on that data. The data or variables
defined within a class are called instance variables and the code that operates on this data is known
as methods.
A simple class example
class Student
{
String USN,name , branch; int phoneno;
}
Object is an instance of a class created using a new operator. The new operator returns a reference to a
new instance of a class. This reference can be assigned to a reference variable of the class. The process
of creating objects from a class is called instantiation. An object encapsulates state and behavior. An
object reference provides a handle to an object that is created and stored in memory. In Java, objects can
only be manipulated via references, which can be stored in variables. Creating variables of your class
type is similar to creating variables of primitive data types, such as integer or float. Each timeyou create
an object, a new set of instance variables comes into existence which defines the characteristics of that
object. If you want to create an object of the class and have the reference variable associated with this
object, you must also allocate memory for the object by using the new operator. This process is called
instantiating an object or creating an object instance. In following statement obj is instance/object of
Student class.
An array of objects is created just like an array of primitive type data items in the following
way.
However, in this particular case, we may use a for loop since all Student objects are created
with the same default constructor.
Constructor
Constructor in java is a special type of method that is used to initialize the object. Java
constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
A constructor that have no parameter is known as default constructor.
Student()
{
//block of code
}
Object creation:
Student obj=new Student();
Object creation:
Student4 s1 = new Student4(111,"Karan");
PROGRAM
/* 1b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods
to demonstrate its working. */
import java.util.*;
class arrayStack
{
int arr[];
int top, max;
arrayStack(int n)
{
max = n;
arr = new int[max];
top = -1;
}
void push(int i)
{
if (top == max - 1)
System.out.println("Stack Overflow");
else
arr[++top] = i;
}
void pop()
{
if (top == -1)
{
System.out.println("Stack Underflow");
}
else
{
int element = arr[top--];
System.out.println("Popped Element: " + element);
}
}
void display()
{
System.out.print("\nStack = ");
if (top == -1)
{
Dept of ISE, SJCIT Page 10
System.out.print("Empty\n");
return;
}
for (int i = top; i >= 0; i--)
System.out.print(arr[i] + " ");
System.out.println();
}
}
class Stack
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Size of Integer Stack ");
int n = scan.nextInt();
boolean done = false;
arrayStack stk = new arrayStack(n);
char ch;
do
{
System.out.println("\nStack Operations");
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. display");
System.out.println("4. Exit");
int choice = scan.nextInt();
switch (choice)
{
case 1:
System.out.println("Enter integer element to push");
stk.push(scan.nextInt());
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:
done = true;
break;
default:
System.out.println("Wrong Entry \n ");
break;
}
} while (!done);
}
}
OUTPUT
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack Overflow
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack = 5 4 3 2 1
Stack Operations
1. push
2. pop
3. display
4. Exit
Popped Element: 5
Stack Operations
1. push
2. pop
3. display
4. Exit
Popped Element: 4
Stack Operations
1. push
2. pop
3. display
4. Exit
Popped Element: 3
Stack Operations
1. push
2. pop
3. display
4. Exit
Popped Element: 2
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack = 1
Stack Operations
1. push
2. pop
3. display
4. Exit
Popped Element: 1
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack Underflow
Stack Operations
1. push
2. pop
3. display
4. Exit
Stack = Empty
Stack Operations
1. push
2. pop
3. display
4. Exit
EXPERIMENT 2A
PROGRAM STATEMENT:
Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this
class by writing three subclasses namely Teaching (domain, publications), Technical (skills),
and Contract (period). Write a Java program to read and display at least 3 staff objects of all
three categories.
CONCEPT:
Here in this given problem we shall use inheritance for extending Staff class into: Teaching, Technical
and Contract 3 subclasses using extends keyword. Each class is having the variables as given in the
bracket. We will import the util package Scanner class to read 3 objects of each class. Create a
constructor of Staff class to initialize StaffId, Name, Phone, Salary. And one display function into the
Staff class to display the entered values. All the data members of Staff will be inherited in Teaching,
Technical and Contract using super keyword that calls the super class constructor to base class. Other
additional data members of the subclasses would be initialized using there own constructor. Also along
with there own constructors all 3 subclasses will have there own display method that invokes display
method of super class Staff. Now in main() method using Scanner class we will read the values
accordingly. To display these values we will create array of object of size 3 for each subclassTeaching,
Technical and Contract. Using this array of objects we will display the values entered previously by
invoking display method of each subclass. Below is the program that demonstrates the same.
PROGRAM:
/** Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this
class by writing three subclasses namely Teaching (domain, publications), Technical (skills),
and Contract (period).
Write a Java program to read and display at least 3 staff objects of all three categories.*/
import java.util.Scanner;
class Staff
{
String StaffID, Name, Phone, Salary;
void read()
{
System.out.println("Enter StaffID");
StaffID = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
System.out.println("Enter Salary");
Salary = input.nextLine();
}
void display()
{
System.out.printf("\n%-15s", "STAFFID: ");
System.out.printf("%-15s \n", StaffID);
System.out.printf("%-15s", "NAME: ");
System.out.printf("%-15s \n", Name);
System.out.printf("%-15s", "PHONE:");
System.out.printf("%-15s \n", Phone);
System.out.printf("%-15s", "SALARY:");
System.out.printf("%-15s \n", Salary);
}
}
void read_Teaching()
{
super.read(); // call super class read method
System.out.println("Enter Domain");
Domain = input.nextLine();
System.out.println("Enter Publication");
Publication = input.nextLine();
}
void display()
{
super.display(); // call super class display() method
System.out.printf("%-15s", "DOMAIN:");
System.out.printf("%-15s \n", Domain);
System.out.printf("%-15s", "PUBLICATION:");
System.out.printf("%-15s \n", Publication);
}
}
{
String Skills;
void read_Technical()
{
super.read(); // call super class read method
System.out.println("Enter Skills");
Skills = input.nextLine();
}
void display()
{
super.display(); // call super class display() method
System.out.printf("%-15s", "SKILLS:");
System.out.printf("%-15s \n", Skills);
}
}
void read_Contract()
{
super.read(); // call super class read method
System.out.println("Enter Period");
Period = input.nextLine();
}
void display()
{
super.display(); // call super class display() method
System.out.printf("%-15s", "PERIOD:");
System.out.printf("%-15s \n", Period);
}
}
class Staffdetails
{
public static void main(String[] args)
{
int n = input.nextInt();
System.out.println();
System.out.println("-----TECHNICAL STAFF DETAILS ---- ");
for (int i = 0; i < n; i++)
{
stech[i].display();
}
System.out.println();
System.out.println("-----CONTRACT STAFF DETAILS ---- ");
for (int i = 0; i < n; i++)
{
scon[i].display();
}
input.close();
}
}
STAFF DETAILS:
STAFFID: 111
NAME: MAHESH n
PHONE: 9916130045
SALARY: 40000
DOMAIN: ise
PUBLICATION: ijaret
STAFFID: 222
NAME: kumar
PHONE: 984512345
SALARY: 10000
SKILLS: c/c++
STAFFID: 123
NAME: rajesh
PHONE: 789123545
SALARY: 8000
PERIOD: 1 year
EXPERIMENT 2B
PROGRAM STATEMENT
Write a Java class called Customer to store their name and date_of_birth. The date_of_birth
format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy>
and display as <name,dd,mm,yyyy> using StringTokenizer class considering the delimiter
character as “/”.
CONCEPT
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way
to break string.The StringTokenizer methods do not distinguish among identifiers, numbers,
and quoted strings, nor do they recognize and skip comments. The set of delimiters (the
characters that separate tokens) may be specified either at creation time or on a per-token
basis.
Constructor Description
creates StringTokenizer with
StringTokenizer(Strin str) specified string.
StringTokenizer(String str, String delim) creates StringTokenizer with specified string and
delimiter.
String nextToken(String delim) returns the next token based on the delimeter.
PROGRAM :
/* 2b. Write a Java class called Customer to store their name and date_of_birth. The date_of_birth
format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy> and display as
<name, dd, mm, yyyy> using StringTokenizer class considering the delimiter character as “/”.
*/
import java.util.Scanner;
import java.util.StringTokenizer;
OUTPUT:-
rajesh,05/04/1984
rajesh,05,04,1984
EXPERIMENT 3A
PROGRAM STATEMENT
Write a java program to read two integers and b. Compute a/b and print when b is not
zero. Raise an exception when b is equal to zero.
CONCEPT
Exception Handling
1. An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
2. All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
3. The code which is prone to exceptions is placed in the try block. When an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should
be immediately followed either by a catch block or finally block.
PROGRAM
/* 3a. Write a Java program to read two integers a and b. Compute a/b and print, when b is
not zero. Raise an exception when b is equal to zero.*/
import java.util.Scanner;
class exception
{
a = input.nextInt();
b = input.nextInt();
try
{
result = a / b;
System.out.println("Result = " + result);
}
catch (ArithmeticException e)
{
System.out.println("Exception caught: Division by zero.");
}
}
}
OUTPUT
RUN1
Input two integers
4
5
Result = 0
RUN2
Input two integers
5
4
Result = 1
RUN3
Input two integers
5
4
Result = 1
EXPERIMENT 3B
PROGRAM STATEMENT
Write a Java program that implements a multi-thread application that hashtree threads. First
thread generates a random integer for every 1 second; second thread computes the square of
the number and prints; third thread will print the value of cube of the number.
CONCEPT:
Thread is basically a lightweight sub-process, a smallest unit of processing. Java is a multi-threaded
programming language which means we can develop multi-threaded program using Java. A multi-
threaded program contains two or more parts that can run concurrently and each part can handle a
different task at the same time making optimal use of the available resources specially when your
computer has multiple CPUs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its task
or otherwise terminates.
Synchronization :
Inter thread communication is important when you develop an application where two or more threads
exchange some information. At times when more than one thread try to access a shared resource, we
need to ensure that resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. To do this we can use either Synchronized block or Synchronized
method.
There are three simple methods which makes thread communication possible, listed below – \
3 Wakes up all the threads that called wait( ) on the same object.
These methods have been implemented as final methods in Object, so they are available in all
the classes. All three methods can be called only from within a synchronized context.
PROGRAM
MultiThread.java
/* 3b. Write a Java program that implements a multi-thread application that has three threads. First
thread generates a random integer for every 1 second; second thread computes the square of the number and
prints; third thread will print the value of cube of the number */
import java.util.Random;
class SquareThread implements Runnable
{
int x;
SquareThread(int x)
{
this.x = x;
}
CubeThread(int x)
{
this.x = x;
}
{
Random r;
Thread t2, t3;
while (true)
{
num = r.nextInt(10);
System.out.println("Main Thread and Generated Number is " + num);
t2 = new Thread(new SquareThread(num));
t2.start();
Thread.sleep(1000);
System.out.println(" ");
}
}
catch (Exception ex)
{
System.out.println("Interrupted Exception");
}
}
}
}
}
OUTPUT
Main Thread and Generated Number is 3
EXPERIMENT 4
PROGRAM STATEMENT
Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n > 5000 and record the time taken to sort.
Plot a graph of the time taken versus n on graph sheet. The elements can be read from a file
or can be generated using the random number generator. Demonstrate using Java how the
divide- and-conquer method works along with its time complexity analysis: worst case, average
case and best case.
CONCEPT
Divide and Conquer: In divide and conquer approach, the problem in hand, is divided into
smaller sub-problems and then each problem is solved independently. When we keep on
dividing the subproblems into even smaller sub-problems, we may eventually reach a stage
where no more division is possible. Those "atomic" smallest possible sub-problem (fractions)
are solved. The solution of all sub-problems is finally merged in order to obtain the solution
of an original problem.
Quick Sort divides the array according to the value of elements. It rearranges elements of a given
array A[0..n-1] to achieve its partition, where the elements before position s are smaller
than or equal to A[s] and all the elements after position s are greater than or equal to
A[s].
Algorithm :
Partition(A[l..r])
//Partition a subarray by using its first element as its pivot
//Input:A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and r (l<r)
//Output:A partition of A[l..r],with the split position returned as this function’s value
{
Dept of ISE, SJCIT Page 44
Design & Analysis of Algorithm Lab Manual
2020
p ← A[l]
i ← l; j ← r+1 repeat
{
repeat i ← i+1 until A[i] >=p
repeat j ← j-1 until A[j] <=p
swap(A[i],A[j]) } until i>=j
swap(A[i],A[j]) // undo last swap when i>=j
swap(A[l],A[j]) return j
}
PROGRAM
/*Program 4.
Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n > 5000 and record the time taken to
sort. Plot a graph of the time taken versus n on graph sheet. The elements can be read
from a file or can be generated using the random number generator. Demonstrate using
Java how the divide-and-conquer method works along with its time complexity analysis:
worst case, average case and best case.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
System.out.println("Input Array:");
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
// set start time
long startTime = System.nanoTime();
QuickSortAlgorithm(0, n - 1);
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println("\nSorted Array:");
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
System.out.println("Time Complexity in ms for n=" + n + " is: " + (double) elapsedTime / 1000000);
}
}
a[p] = a[j];
a[j] = pivot;
QuickSortAlgorithm(p, j - 1);
QuickSortAlgorithm(j + 1, r);
}
}
}
OUTPUT
Enter Max array size: 10
Enter the array elements:
10
4
6
8
1
3
5
2
9
7
Input Array:
10 4 6 8 1 3 5 2 9 7
Sorted Array:
1 2 3 4 5 6 7 8 9 10
Time Complexity in ms for n=10 is: 0.009056
EXPERIMENT 5
PROGRAM STATEMENT
Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n > 5000, and record the time taken to sort.
Plot a graph of the time taken versus n on graph sheet. The elements can be read from a file
or can be generated using the random number generator. Demonstrate using Java how the
divide- and-conquer method works along with its time complexity analysis: worst case, average
case and best case.
CONCEPT
Merge sort is a perfect example of a successful application of the divide-and-conquer
technique.
Split array A[1..n] in two and make copies of each half in arrays B[1.. n/2 ] and C[1..
n/2 ]
Sort arrays B and C
Merge sorted arrays B and C into array A as follows:
a) Repeat the following until no elements remain in one of the arrays:
(i) compare the first elements in the remaining unprocessed portions of the
arrays
(ii) copy the smaller of the two into A, while incrementing the index indicating the
unprocessed portion of that array
b) Once all elements in one of the arrays are processed, copy the remaining
unprocessed elements from the other array into A.
i ← 0; j←0; k←0
while i<p and j<q do
{
if B[i] <= C[j]
A[k] ← B[i]; i← i+1
else
A[k] ← C[j];
j← j+1 k ← k+1;
}
if i=p
copy C [j…q-1] to A[k…p+q-1]
else
copy B [i…p-1] to A[k…p+q-1]
}
Complexity:
All cases have same efficiency: Θ( n log n)
Number of comparisons is close to theoretical minimum for comparison-based sorting: log n
! ≈ n lg n - 1.44 n
PROGRAM:
/* Program 5
Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n > 5000, and record the time taken to
sort. Plot a graph of the time taken versus n on graph sheet. The elements can be read
from a file or can be generated using the random number generator. Demonstrate using
Java how the divide-and-conquer method works along with its time complexity analysis:
worst case, average case and best case.
*/
import java.util.Random;
import java.util.Scanner;
if (h > mid)
for (k = j; k <= high; k++)
b[i++] = a[k];
else
OUTPUT
Enter Max array size: 20
208
536
750
299
530
689
73
819
528
815
49
7
413
209
423
861
682
744
885
24
Time Complexity (ms) for n = 20 is : 0.304288
Sorted Array (Merge Sort):
7 24 49 73 208 209 299 413 423 528 530 536 682 689 744 750 815 819 861 885
EXPERIMENT 6A
PROGRAM STATEMENT
Implement in Java, the 0/1 Knapsack problem using Dynamic Programming method
CONCEPT
Dynamic-Programming Solution to the 0-1 Knapsack Problem: Dynamic programming is used
where we have problems, which can be divided into similar sub-problems, so that their results
can be re-used. Mostly, these algorithms are used for optimization. Before solving the in-hand
sub-problem, dynamic algorithm will try to examine the results of the previously solved sub-
problems. The solutions of sub-problems are combined in order to achieve the
best solution.wi.In the knapsack problem we are given a set of n items, where each item i is
specified by a size and a value vi. We are also given a size bound W (the size of our knapsack).
The goal is to find the subset of items of maximum total value such that sum of their sizes is
at most W (they all fit into the knapsack).Now, instead of being able to take a certain weight
of an item, you can only either take the item or not take the item.
Algorithm:
//Output: V(n,W)
set V(i,0) = 0
• Repeat for j = 0 to W
Set V(0,j) = 0
• Repeat for i = 1 to n
repeat for j = 1 to W
ww v
i i i
Print V(n,W)
PROGRAM
/* Knapsack DP */
import java.util.Scanner;
else
{
V[i][j] = V[i - 1][j];
Keep[i][j] = 0;
}
OUTPUT
Knapsack Problem - Dynamic Programming Solution:
Enter the max capacity of knapsack:
15
Enter number of objects:
4
Enter Weights:
2
5
Dept of ISE, SJCIT Page 58
Dept of ISE, SJCIT Page 59
Design & Analysis of Algorithm Lab Manual
2020
7
3
Enter Profits:
23
78
34
12
Items =
3
2
1
EXPERIMENT 6B
PROGRAM STATEMENT
Implement in Java, the Fractional Knapsack problem using Greedy method
CONCEPT
Greedy Solution to the Fractional Knapsack Problem
The basic idea of greedy approach is to calculate the ratio value/weight for each item and sort the item
on basis of this ratio. Then take the item with highest ratio and add them until we can’t add the next
item as whole and at the end add the next item as much as we can. This will always be optimal solution
of this problem.
Algorithm:
Assume knapsack holds weight W and items have value vi and weight wi
Rank items by value/weight ratio: vi / wi Thus: vi / wi ≥ vj / wj, for all i ≤ j
Consider items in order of decreasing ratio
Take as much of each item as possible
PROGRAM
/* Knapsack Greedy */
import java.util.Scanner;
class KObject
{ // Knapsack object details
float w;
float p;
float r;
}
public class KnapsackGreedy2
{
static final int MAX = 20; // max. no. of objects
static int n; // no. of objects
static float M; // capacity of Knapsack
ReadObjects(obj);
Knapsack(obj);
scanner.close();
}
if (kobj[i].w > U)
break;
else
{
x[i] = 1;
totalprofit = totalprofit + kobj[i].p;
U = U - kobj[i].w;
}
}
10
9
6
14
Enter Profits:
45
67
12
78
54
i=2
The Solution vector, x[]:
1.0 1.0 0.64285713 0.0 0.0
Total profit is = 179.7143
EXPERIMENT 7
PROGRAM STATEMENT
From a given vertex in weighted connected graph, find shortest path to other vertices using
Dijkstras algorithm. Write the program in java.
CONCEPT
It is a greedy algorithm which finds the shortest path from the source vertex to all other vertices of the
graph.
Steps
1. Input a cost matrix for graph. Read the source vertex and n from user
2. Create the array d [1…n] which stores the distance from source vertex to all other
vertices of graph. Initialize distance to source vertex as 0(i.e. d [source] =0) and
remaining vertices as 999.
3. Create the array visited [1…n] which keeps track of all the visited nodes. Visit the
source vertex and initialize visited [source] =1.
4. For all adjacent vertices[vi,vi+1,…] for source vertex calculate distance using formula
d[vi]=min(d[vi], d[source]+ cost[source][v1]). Update the array d [1…n].
5. For all adjacent vertices find vertex vi which has minimum distance from source
vertex.
6. Initialize source = vi. Repeat the steps 4, 5 until there all some vertices which are
unvisited.
7. Stop
Example
PROGRAM
/* Dijikstra's */
import java.util.*;
OUTPUT
Enter the number of vertices:
4
Enter the cost adjacency matrix:
999 1 6 4
999 999 999 2
999 3 999 999
999 999 1 999
Enter starting vertex:
1
2:1
3:4
4:3
EXPERIMENT 8
PROGRAM STATEMENT
Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal’s
algorithm. Implement the program in Java. Use Union-Find algorithm in your program.
CONCEPT
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. Hence, a spanning tree does not have cycles and it cannot be
disconnected.
By this definition, we can draw a conclusion that every connected and undirected Graph G has at least one
spanning tree. A disconnected graph does not have any spanning tree, as it cannot be spanned to all its
vertices.
We found three spanning trees off one complete graph. A complete undirected graph
can have maximum nn-2 number of spanning trees, where n is the number of nodes. In the above
addressed example, 33−2 = 3 spanning trees are possible.
We now understand that one graph can have more than one spanning tree. Following are a
few properties of the spanning tree connected to graph G −
All possible spanning trees of graph G, have the same number of edges and vertices.
Removing one edge from the spanning tree will make the graph disconnected, i.e. the
spanning tree is minimally connected.
Adding one edge to the spanning tree will create a circuit or loop, i.e. the spanning
tree is maximally acyclic.
Kruskal's algorithm to find the minimum cost spanning tree uses the greedy approach. This
algorithm treats the graph as a forest and every node it has as an individual tree. A tree connects
to another only and only if, it has the least cost among all available options and does not violate
MST properties.
In case of parallel edges, keep the one which has the least cost associated and remove all
others.
The least cost is 2 and edges involved are B,D and D,T. We add them. Adding them does not
violate spanning tree properties, so we continue to our next edge selection.
Next cost is 3, and associated edges are A,C and C,D. We add them again −
Next cost in the table is 4, and we observe that adding it will create a circuit in the graph. −
We ignore it. In the process we shall ignore/avoid all edges that create a circuit.
We observe that edges with cost 5 and 6 also create circuits. We ignore them and move on.
Now we are left with only one node to be added. Between the two least cost edges available 7
and 8, we shall add the edge with cost 7.
By adding edge S,A we have included all the nodes of the graph and we now have minimum cost spanning
tree.
PROGRAM
/* 8. Kruskals */
import java.util.Scanner;
{
ReadMatrix();
Kruskals();
}
int i, j;
cost = new int[MAX][MAX];
}
u = find(u);
v = find(v);
if (u != v)
{
uni(u, v);
System.out.println(ne++ + "edge (" + a + "," + b + ") =" + min);
mincost += min;
}
cost[a][b] = cost[b][a] = 999;
}
System.out.println("Minimum cost :" + mincost);
}
OUTPUT
Implementation of Kruskal's algorithm
Enter the no. of vertices
4
Enter the cost adjacency matrix
999 1 6 4
999 999 999 2
999 3 999 999
999 999 1 999
The edges of Minimum Cost Spanning Tree are
1edge (1,2) =1
2edge (4,3) =1
3edge (2,4) =2
Minimum cost :4
EXPERIMENT 9
PROGRAM STATEMENT
Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim’s
algorithm.
CONCEPT
Prim's algorithm to find minimum cost spanning tree uses the greedy approach. Prim's
algorithm shares a similarity with the shortest path first algorithms.
Prim's algorithm, in contrast with Kruskal's algorithm, treats the nodes as a single tree
and keeps on adding new nodes to the spanning tree from the given graph.
To contrast with Kruskal's algorithm and to understand Prim's algorithm better, we
shall use the same example −
Remove all loops and parallel edges from the given graph. In case of parallel edges, keep the
one which has the least cost associated and remove all others.
Now, the tree S-7-A is treated as one node and we check for all edges going out from it. We
select the one which has the lowest cost and include it in the tree.
After this step, S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all
the edges again. However, we will choose only the least cost edge. In this case, C-3-D is the
new edge, which is less than other edges' cost 8, 6, 4, etc.
After adding node D to the spanning tree, we now have two edges going out of it having the
same cost, i.e. D-2-T and D-2-B. Thus, we can add either one. But the next step will again yield
edge 2 as the least cost. Hence, we are showing a spanning tree with both edges included.
PROGRAM
/* 9. Prim's */
import java.util.Scanner;
int i, j;
cost = new int[MAX][MAX];
System.out.println("\n Enter the number of nodes:");
n = scan.nextInt();
System.out.println("\n Enter the adjacency matrix:\n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
{
cost[i][j] = scan.nextInt();
if (cost[i][j] == 0)
cost[i][j] = 999;
}
}
OUTPUT
Enter the number of nodes:
4
999 7 2 4
999 999 999 5
999 4 999 999
999 999 1 999
Edge1:(1,3)cost:2
Edge2:(1,4)cost:4
Edge3:(3,2)cost:4
Minimun cost10
EXPERIMENT 10A
PROGRAM STATEMENT
Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
CONCEPT
The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem.
The problem is to find shortest distances between every pair of vertices in a given edge
weighted directed Graph. Following Algorithm is used to find shortest path:
given: w[i][j] is the wieghted matrix that contains weights k is the iteration variable for
intermidiate vertices Following is the algorithm
function floyd for i=1 to n for j=1 to n
w[i][j]=infinity//if entered w[i][j] == 0 for each edge (i,j) in E
dmatrix[i][i] = amatrix[i][j];//copy the entered weighted matrix to distance matrix //calculate
distance matrix
for k=1 to n for i=1 to n for j=1 to n
if (dmatrix[i][k] + dmatrix[k][j]< dmatrix[i][j])
dmatrix[i][j] = dmatrix[i][k] + dmatrix[k][j];
PROGRAM
import java.util.Scanner;
public class FloydsClass
{
static final int MAX = 20; // max. size of cost matrix
static int a[][]; // cost matrix
static int n; // actual matrix size
{
for (int j = 1; j <= n; j++)
{
a[i][j] = scanner.nextInt();
}
}
scanner.close();
}
OUTPUT
Enter the number of vertices
4
Enter the Cost Matrix (999 for infinity)
999 1 4 6
999 999 7 4
2 999 999 3
999 999 999 999
The All Pair Shortest Path Matrix is:
6 1 4 5
9 10 7 4
2 3 6 3
EXPERIMENT 10B
PROGRAM STATEMENT
CONCEPT
Given a set of cities and distance between every pair of cities, the problem is to find the
shortest possible route that visits every city exactly once and returns to the starting point. Note the
difference between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there
exist a tour that visits every city exactly once. Here we know that Hamiltonian Tour exists (because
the graph is complete) and in fact many such tours exist, the problem is to find a minimum weight
Hamiltonian Cycle.
For example, consider the above graph. A TSP tour in the graph is 1-2-4-3-1. The cost of the
tour is 10+25+30+15 which is 80.
PROGRAM
/* 10b. TSP - DP */
import java.util.Scanner;
{
int cost = infinity;
int c[][] = new int[MAX][MAX]; // cost matrix
int tour[] = new int[MAX]; // optimal tour
int n; // max. cities
System.out.println("Travelling Salesman Problem using Dynamic Programming\n");
System.out.println("Enter number of cities: ");
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
System.out.println("Enter Cost matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
c[i][j] = scanner.nextInt();
if (c[i][j] == 0)
c[i][j] = 999;
}
for (int i = 0; i < n; i++)
tour[i] = i;
cost = tspdp(c, tour, 0, n);
// print tour cost and tour
System.out.println("Minimum Tour Cost: " + cost);
System.out.println("\nTour:");
for (int i = 0; i < n; i++)
{
System.out.print(tour[i] + " -> ");
}
System.out.println(tour[0] + "\n");
scanner.close();
}
OUTPUT
Travelling Salesman Problem using Dynamic Programming
0124
1 0 999 1
2 999 0 1
4110
Minimum Tour Cost: 5
Tour:
0 -> 1 -> 3 -> 2 -> 0
EXPERIMENT 11
PROGRAM STATEMENT
Find a subset of a given set S = {sl,s2,. ... ,sn} of n positive integers whose sum is equal to a given
positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two
solutions{1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesn't
have a solution.
CONCEPT
Subset-Sum Problem is to find a subset of a given set S= {s1, s2… sn} of n positive integers
whose sum is equal to a given positive integer d. It is assumed that the set’s elements are
sorted in increasing order. The state-space tree can then be constructed as a binary tree and
applying backtracking algorithm, the solutions could be obtained. Some instances of the
problem may have no solutions.
PROGRAM
import java.util.Scanner;
else
SumofSub(0, 0, sum);
scanner.close();
}
OUTPUT
EXPERIMENT 12
PROGRAM STATEMENT
Design and implement in java to find all Hamiltonian Cycles in a connected undirected graph
G with n vertices using backtracking principle.
CONCEPT
A Hamiltonian cycle, Hamiltonian circuit is a cycle that visits each vertex exactly once
(except for the vertex that is both the start and end, which is visited twice). A graph that contains
a Hamiltonian cycle is called a Hamiltonian graph.
Following is one way of checking whether a graph contains a Hamiltonian Cycle or not.
A Hamiltonian Path in a graph having N vertices is nothing but a permutation of the vertices of the
graph [v1, v2,
v3, ...... vN-1, v N], such that there is an edge between vi and vi+1 where 1 ≤ i ≤ N-1. So it can be
checked for all permutations of the vertices whether it represents a Hamiltonian Cycle or not.
INPUT OUTPUT
PROGRAM
/* 12. Hamiltonian cycle */
import java.util.Scanner;
System.out.println("\nSolution:");
hamiltonian.HamiltonianMethod(2);
hamiltonian.printNoSlnPossible();
scanner.close();
}
void HamiltonianMethod(int k)
{
while (true)
{
NextValue(k, G, x, n);
if (x[k] == 0)
return;
if (k == n)
{
for (int i = 1; i <= k; i++)
System.out.print(x[i] + " ");
System.out.println(x[1]);
System.out.println();
found = true;
return;
}
else
HamiltonianMethod(k + 1);
}
}
2 and 3: 1
2 and 4: 1
3 and 4: 1
Solution:
12341
13241
14231
ADDITIONAL PROGRAMS
1) All pair shortest paths problem using Floyd’s algorithm. Parallelize this algorithm , implement
it using OPenMP and determine the speed-up achieved.
.
# include< stdio.h>
# include <omp.h>
void floyds(int a[10][10],int n);
int min(int a,int b);
int main( )
{
int thread_id,i,j,n,a[10][10];
double starttime,endtime;
system(“clear”);
printf(“ Enter the no of vertices”);
scanf(“%d”,&n);
printf(“Enter the weight matrix \n”);
printf(“ Enter 0 for self loops and 999 for no edge\n”);
for ( i=1; i<=n; i++ )
for ( j=1; j<=n; j++ )
{
scanf(“%d”,&a[i][j]);
}
starttime=omp_get_wtime();
floyds(a,n);
endtime= omp_get_wtime();
printf(“Speed up achieved is %f”,endtime-starttime);
}
int min( int a,int b)
{
return(a<b ?a:b);
}
void floyds(int a[10][10],int n)
{
int b[10][10],i,j,k,thread_id;
for ( i=1; i<=n; i++ )
for ( j=1; j<=n; j++ )
b[i][j]=a[i][j];
omp_set_num_threads(2);
# pragma omp parallel for shared(b) private(i,j,k)
for ( i=1; i<=n; i++ )
{
for ( j=1; j<=n; j++ )
for(k=1; k<=n; k++)
{
thread_id=omp_get_thread_num();
b[i][j]=min(b[i][j],b[i][k]+b[k][j]);
printf(“Thread %d:b[%d][%d]=%d\n”,thread_id,i,j,b[i][j]);
}
}
printf(“ All pairs shortest path \n”);
for ( i=1; i<=n; i++ )
{
for ( j=1; j<=n; j++ )
printf(“%5d”, b[i][j]);
printf(“\n”);
}
return;
}
Output:
Enter the Number of vertices
3
Enter 0 for self loops and 999 for noedges
0 5 999
999 0 3
2 999 0
All pairs shortest path is
058
503
270
# include< stdio.h>
# include < conio.h>
# include <process.h>
#include <math.h >
int x[10];
void main( )
{
int k, i, j, n, count=1;
int place (int);
clrscr( );
printf( “ Enter the number of Queens\n”);
scanf(“%d”,&n);
if( n= = 0 || n= = 2 || n= = 3 )
printf(“ No Solution”);
else
k=1;
x[1]=0;
while(k)
{
x[k]= x[k]+1;
while( ( x[k] <=n) && (!place(k) ) )
x[k]= x[k]+1;
if( x[k]<=n )
{
if(k= = n)
{
getch( );
printf(“Solution %d \n”,count++);
for ( i=1; i<=n; i++ )
{
for ( j=1; j<x[i]; j++ )
printf(“ * “);
printf(“ Q” );
for ( j=x[i]+1; j<=n; j++ )
printf(“ * “);
printf(“ \n” );
}
}
else
{
k + = 1;
x[k]=0;
}
}
else
k - = 1;
}
getch( );
}
Output:
Enter the no of queens
4
Solution 1
Q**
***Q
Q***
**Q*
Solution 2
**Q*
Q***
***Q
*Q**
Decrease and Conquer:Explain any problem which can be Solved Using decrease and
Conquer,EX:DFS,BFS,Topological Sorting.
Limitations of Algorithms:Explain few things about Decision trees and its use in solving a
Problem.
Coping with Limitations of Algorithms:Explain Backtracking and one problem which illustrates
about Backtacking method and Wind Up.
12. What is the Time Complexeity of Bubble Sort,Selection Sort ,Merge Sort,Quick Sort?(L3)
Bubble Sort-n2,
Selection Sort- n2
Merge Sort-nlog.n
Quick Sort -nLogn, Worst case for Quick Sort- n2
13. Which sorting agorithm is more Efficient and why?(L3)
Quick Sorting is More Efficient ,because this algorithm is instable algorithm and
inplace.
14. What do you mean by the term Instable Algorithms?(L2)
The Instable Algorithms are one, which divides the array as certainly depending upon pivot or key element
and hence i index precedes index j
15. Which algorithms are faster?(L3)
Instable Algorithms are much Faster compared to Stable Algorithms.
16. For what type of instance Merge sort do better than Quick Sort?(L3)
For a Larger input and a sorted input values.
17. For what type of instance Quick sort do better than Merge Sort? (L3)
For Smaller Set of input numbers.
18. What are Inplace Algorithms?
Inplace Algorithms are the one which doesn't occupies Extra Space.
19. Write the order of growth terms as per the time Execution in Ascending Order.(L3)
logn,n,nlogn,n2,n3,..... nn,2n,n!
20. What is Brute Force Technique? When We Should Use? (L3)
Brute Force is a straight Forward Technique to solve a problem, We used to solve a Problem through
this approach when we don't have sufficient data to solve a problem in Efficient Way.
21. What is the difference between Divide and Conquer, Decrease and Conquer? (L2)
Divide and Conquer can be solved to solve a problem with a larger data set and when there is no
dependency between any of the data sets.
Divide and Solve as Small as Small sets.
Conquer or Merge it get one final resultant data set.
Decrease and Conquer is almost similar to Divide and Conquer but we are finding a solutions to the
problem in a different variations,EX:Decrease by Constant (Usually by One),Decrease by Constant factor
which is almost similar to Divide and Conquer Technique(Usually by two),Decrease by Variable(The
Dividing Criteria changes for each iteration depends upon the data set.
22. Define Greedy Technique. (L2)
Greedy Technique is always applied for the problem of the type optimization type, which reduces loss
and increases profit.
23. Define Optimal and Feasible Solution. (L2)
Optimal Solution is a solution which is best among N Feasible Solution.
Feasible Solution is a solution which Satisfies a Problem Constraints/conditions.
24. Can A Problem solved by all the algorithmic Techniques.(L3)
Yes,but some problems will give better results with some Algorithmic Technique and it may give worst
result when it is applied with other technique.
25. State and Explain Knapsack Problem. (L2)
Filling the Maximum number of items to the Knapsack (Container) Which Increases the profit and
decreases the Loss.
26. State Few Algorithmic Techniques which you have studied. (L2)
Brute Force Technique
Divide and Conquer
Greedy Technique
Dynamic Programming
Decrease and Conquer
27. Which one is Most Admired algorithmic Technique?(L3)
Dynamic Programming.
28. What is Spanning tree and Minimum Spanning tree?(L2)
A tree Without Cycles are called as Spanning tree .
A Minimum Spanning Tree is a spanning tree which yeilds the very less Cost when all the edges cost
summed up.
29. How Many Spanning Tree can a Tree can have?(L3)
A tree can have 1 to many number of Possible ways of Spanning Tree.
30. Differentiate between Prims and Kruskals Algorithm for finding MST.(L2)
In Prims We consider any one vertex in the graph as Source and We compute the distance from that source
to other vertices ,after computing the vertices which has minimum value among (n-1) vertices is added to
tree vertices and that respective edges added to tree Edges Set.The above mentioned Process continues till
we reach (n-1) vertices.
In Kruskals we first arrange the edges in Ascending Order and then we start to form the tree which wont form
cycles,if adding that edges forms cycles then that edges is dropped from adding to tree edges.The above said
process is continues till we reach the count of
(n-1) Vertices.
31. What is the Application of Prims and Kruskals Algorithm?(L3)
In Networks to remove the Cyclicity of the Network.
32. Explain Job Sequencing With Deadlines?(L2)
Placing or scheduling the maximum number of Jobs to a machine without violating the deadlines constraint
of any of the Jobs in Sequence.
33. Why the Name Bubble Sort named?(L3)
Because in first Pass the first highest data will bubbles up,so since the largest element bubbles up
in the first and second largest element bubbles up in the Second pass and so on, so hence the name bubble
sort.
34. Why the Name Selection Sort?(L3)
The Selection sort is named because we initially first select an arrays first element as minimum and will
compare with other elements ,so in pass one first least element goes to the first position and so on so
forth for 2nd,3rd and so on. Selecting
35. What is the difference between Brute force strings matching to Horspool String Matching
Method? (L2)In brute Force we compare each and every element of the text to the pattern by shifting
the text positionby one and in Horspool method we shift it by number of shift positions recorded in the
shift table.
36. Explain Merge Sort?(L2)
In Merge Sort will divide the entire input set by 2 until we reach low<high and later will find a solution to
each item by comparing half of the array data set to the other half array data set and finally we merge it
to form a sinle array(conquer)
37. What is the Basic Operations in Merge sort and Quick sort?(L2)
In Merge Sort the Basic Operations is Comparisions and in Quick sort basic Operations is Partitioning and
hence also known as partitioning sort.
38. Why the Insertion Sort?(L3)
We are Inserting an element to its suitable place by comparing n elements for each pass.
39. What is the Use of DFS and BFS?(L2)
DFS and BFS both used to check the Connectivity of a graph,Cyclicity in a graph,Spanning tree of a
graph.
40. Differentiate between DFS and BFS.(L2)
DFS and BFS are both the Graph Traversing Technique,in which DFS Traverse the Graph in a depth
wise(Vertical) and BFS Traverse the Graph from left to right(Horizontal)
41. Which Data structures used in BFS and DFS.(L2)
BFS USes Queue as its data structure and DFS uses as stack its Data structure.
42. What are back edges in DFS and Cross Edges in BFS.(L2)
Back Edges and Cross edges are the Edges which already visited by a ancestor node.
43. What is Topological Sorting?(L2)
Topological Sorting is a Sorting Technique used for sorting Vertices in the Graph.
44. What is the Conditions necessary for a Topological Sorting? (L3)
For a Topological Sorting the Graph Should be DAG(Directed Acyclic Graph)
45. What are the Different methods used to solve a topological Sorting ?(L3)
(i) Source Removal Method
(ii) Using DFS based Scheme.
46. What is the Use of Topological Sorting?(L3)
Use of Topological Ordering is in the field of Operating System for Scheduling and in
Networks,Automation and Robotics.
47. What is Dijikstra's Algorithm?(L2)
Dijikstra's Algorithm is Used to find the Single shortest Path from source to the other vertex.
48. What is a graph?(L2)
Procedures:It is same as the Functions but we call it Procedures in Assembly languages like
Masm,Tasm.The Size of the Procedures is small Compared to Functions and it uses the Mnemonics like
JLR,ADD,SUB,DIV,CMP and etc.
SubRoutines: Same as above(Procedures,used in languages like FORTRAN)
Macros:Macros are the functions Which is Small in Size ,usually used as Library files ,it is invoked only
if it is needed.
75. Name Standard Input,Standard output,Standard Error.(L2)
Standard Input-Keyboard
Standard Output-Monitor
Standard Error-Monitor
76. What are standard I/O functions? (L2)
Printf() and Scanf()
77. What is the use of using getch() in every Program?Does it Impact to the ouput of the Program?
(L3)
Getch() is a informal input functions which makes the ouput screen to be displayed until we enter a
character(Read-input operations)
Getch() doesn’t Impact in anyways
78. What are Command line Arguments (L2)
The Arguments which are passed at command line to the function main()
Are called as Comman line Arguments.
d. Record write up