CS3401 Algorithms Exps

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

EX.

NO : 1
IMPLEMENTATION OF LINEAR SEARCH

AIM:
To write a program to implement Linear Search.

ALGORITHM:
Step 1: Start
Step 2: Declare SIZE, I, POS, KEY
Step 3: Initialize POS = -1, I=0
Step 4: Get Array elements and key
Step 5: Repeat step 5 for I < SIZE
Step 5.1: IF A[I] = KEY
POS = I
BREAK
[END OF IF]
Step 5.2: I = I + 1
[END OF LOOP]
Step 6: IF POS = -1
PRINT "VALUE IS PRESENT"
ELSE
PRINT "VALUE IS NOT PRESENT"
[END OF IF]
Step 7: Stop

PROGRAM:
pos =-1
print("Enter the size : ")
size =int(input())
print(f"Enter {size} elements in a single line : ")
arr =list(map(int,input().split(" ")))
print("Enter the search element : ")
key = int(input())
for i in range(size):
if arr[i] == key:
pos=i
break
if pos==-1:
print(f"Value {key} is not present in the List ")
else:
print(f'The Value {key} is present at index {pos}')

CS3401 | ALGORITHMS
OUTPUT:
Enter the size:
5
Enter 5 elements in a single line:
5 6 71 2 8
Enter the search element:
2
The Value 2 is present at index 3

RESULT:
Thus the program to implement Linear Search is executed successfully and the output is verified.
CS3401 | ALGORITHMS
EX. NO : 2
IMPLEMENTATION OF RECURSIVE BINARY SEARCH

AIM:
To write a program to implement Binary Search using recursive approach.

ALGORITHM:
Step 1: Start
Step 2: Get size (N) and Declare Arr[N]
Step 3: Get Array elements and search value (Key)
Step 4: Intialize Low = 0 and High = N-1
Step 5: Pos = bSearch(Arr,Low,High,Key)
Step 6: Def bSearch(Arr,Low,High)
Step 6.1: Mid = (Low+High)//2
Step 6.2: IF Low > High
Return -1
Step 6.3: ELIF Arr[Mid] = Key
Return Mid
Step 6.4: ELIF Arr[mid] > Key
High = Mid – 1
Step 6.5: ELSE
Low = Mid + 1
Step 6.6: Return bSearch(Arr,Low,High,Key)
Step 7: IF Pos = -1
DISPLAY “Element Not Found”
Step 8: Else
Display “Element Found At Position Pos”
Step 9: Stop

PROGRAM :
def binarySearch(arr,low,high,key):
mid =(low+high)//2
if low > high:
return -1
elif arr[mid] == key:
return mid
elif arr[mid] > key:
high =mid-1
else:
low =mid+1
return binarySearch(arr,low,high,key)
size = int(input("Enter the size : "))
arr = list(map(int,input(f"Enter {size} values in a single Line : ").split(" ")))

CS3401 | ALGORITHMS
key =int(input("Enter search element : "))
low ,high=0,size-1
pos = binarySearch(arr,low,high,key)
if(pos == -1):
print(f"Value {key} is not present in the list")
else:
print(f"Value {key} is present the List at position {pos} ")

OUTPUT:
Enter the size: 11
Enter 11 values in a single Line: 2 3 4 5 6 7 8 9 12 23 45
Enter search element: 45
Value 45 is present the List at position 10

RESULT:
Thus the program to implement Recursive Binary Search is executed successfully and the output is
verified.
CS3401 | ALGORITHMS
EX. NO :3 IMPLEMENTATION OF PATTERN SEARCH USING NAIVE
APPROACH

AIM:
To write a python program to implement Pattern Search which prints all the occurrences of pattern in
a text.

ALGORITM:
Step 1: Start
Step 2: Get Pattern and Text
Step 3 : [Initialize] Set P = len(Pattern) and T = len(Text)
Step 4: [Initialize] I=0, J=0
Step 5: Repeat step 5 While I <= T-P
Step 5.1: J = 0
Step 5.2: Repeat step 5.2 While Pattern[J] = Text[I+J] and J < P
Step 5.2.1: J = J + 1
[END OF WHILE]
Step 5.3 IF J = P
Print "Pattern is found at position I"
Step 5.4: I = I+1
[END OF WHILE]
Step 6: Stop

PROGRAM:
def occurance(text,pattern):
T = len(text)
P =len(pattern)
count=0
for i in range(T-P+1):
j=0
while( j<P and pattern[j] == text[i+j]):
j+=1
if j == P:
print(f "\"{pattern}\" is matches from index {i} to {i+j-1} in \"{text}\"")
count+=1
return count
text =input("Enter the text : ").strip()
pattern =input("Enter the pattern : ").strip()
count =occurance(text,pattern)
if count == 0:
print(f "\"{pattern}\" is not occured in \"{text}\"")
else :
print(f "\"{pattern}\" is occured {count} times in \"{text}\"")

CS3401 | ALGORITHMS
OUTPUT:
Enter the text: Malayalam
Enter the pattern: la
"la" is matches from index 2 to 3 in "Malayalam"
"la" is matches from index 6 to 7 in "Malayalam"
"la" is occured 2 times in "Malayalam"

RESULT:
Thus the program to print all the occurrences of pattern in a text is executed successfully and the
output isverified
CS3401 | ALGORITHMS
EX. NO :4A
IMPLEMENTATION OF INSERTION SORT

AIM:
To write a C program to implement insertion sort.

ALGORITHM:
Step 1: Start
Step 2: Get size(N) and Declare Arr[N] , J , Temp
Step 3: Intialize I = 1
Step 4: Repeat step 4 While I < N
Step 4.1: Set J = I-1
Step 4.2: Temp = Arr[ I ]
Step 4.3: Repeat 4.3 While J > -1 and Arr[ J ] > Temp
Step 4.3.1: Set Arr[J+1] = Arr[ J ]
Step 4.3.2: Set J + = 1
[END OF WHILE]
Step 4.4: Set Arr[J+1] = Temp\
Step 4.5: Set I+=1
[END OF WHILE]
Step 5: Display the Sorted Array
Step 6: Stop

PROGRAM:
#include<stdio.h>
void Insertion_Sort(int[],int);
void print(int[],int);
void Insertion_Sort(int arr[],int size){
int j,temp,i;
for(i=1;i<size;++i){
temp=arr[i];
j=i-1;
while(j>=0 && arr[j]>temp){
arr[j+1]=arr[j];
--j;
}
arr[j+1] = temp;
}
}
void print(int arr[],int size)
for(int i=0;i<size;++i) printf("%d ",arr[i]);
int main(){
int size,i;
printf("Enter the size : ");
scanf("%d",&size);
int arr[size];
for(i=0;i<size;++i) scanf("%d",&arr[i]);
CS3401 | ALGORITHMS
printf("Before the sort : ");
print(arr,size);
Insertion_Sort(arr,size);
printf("\nAfter the sort : ");
print(arr,size);
return 0;
}

OUTPUT:
Enter the size: 8
4 16 21 2 12 2 4 8
Before the sort: 4 16 21 2 12 2 4 8
After the sort: 2 2 4 4 8 12 16 21

RESULT:
Thus the program to implement Insertion Sort is executed successfully and the output isverified.
CS3401 | ALGORITHMS
EX. NO :4B
IMPLEMENTATION OF HEAP SORT

AIM:
To write a program to implement Heap sort.

ALGORITHM:
Step 1: Start
Step 2: Get size(N) and Declare Arr[N]
Step 3: Initialize I = (N/2)-1 [ Last Non Leaf Node]
Step 4: Get N element in the Array
Step 5: Repeat step 5 While I > -1
Step 5.1: MaxHeap(Arr,N,I)
Step 5.2 : I - = 1
[END OF WHILE]
Step 6: Set I = N-1
Step 7: Repeat step 7 While I >=0 [Deletion routine]
Step 7.1 Swap (Arr[0] ,Arr[I])
Step 7.2: MaxHeap(Arr,I,0)
[END OF WHILE]
Step 8: Display the Sorted Array
MaxHeap(Arr,Size,I) [Building and Heapifying Routine]
Step 9: Initialize Max =I , Left =(i*2)+1 and Right =(i*2)+2
Step 10: IF Arr[Left] >Arr[Max] || Arr[Right] > Arr[Max]
Step 10.1: Set Max = Arr[Left] >Arr[Right] ?Arr[ Left] :Arr[Right]
Step 11: IF Max ! = I:
Step 11.1: Swap(Arr[i] ,Max)
Step 11.2 : Repeat MaxHeap(Arr,Size,Max)
Step 12: Stop.

PROGRAM:
#include<stdio.h>
void MaxHeap(int arr[],int size,int i){
int max =i;
int l,r,temp;
l = i*2 +1;
r = i*2 +2;
if(l<size && arr[l]>arr[max])
max=l;
if(r<size && arr[r]>arr[max])
max=r;
if(max!=i)
{
temp =arr[i] ;
arr[i] = arr[max];
arr[max] =temp;
MaxHeap(arr,size,max);
CS3401 | ALGORITHMS
}
}
void print(int arr[],int size)
for(int i=0;i<size;++i) printf("%d ",arr[i]);
int main(){
int size,i,temp;
printf("Enter the size : ");
scanf("%d",&size);
int arr[size];
for(i=0;i<size;++i)
scanf("%d",&arr[i]);
printf("Given elements : ");
print(arr,size) ;
printf("\nAfter Constructing max Heap (In levelorder) : ");
for(i =(size/2)-1;i>=0;--i)
MaxHeap(arr,size,i);
print(arr,size);
printf("\nAfter Sorting : ");
for(i=size-1;i>=1;--i){
temp =arr[0];
arr[0] =arr[i];
arr[i] = temp;
MaxHeap(arr,i,0);
}
print(arr,size) ;
return 0;
}

OUTPUT:
Enter the size: 7
10 3 8 21 4 9 12
Given elements: 10 3 8 21 4 9 12
After Constructing max Heap (In levelorder): 21 10 12 3 4 9 8
After Sorting: 3 4 8 9 10 12 21

RESULT:
Thus the program to implement Heap Sort is executed successfully and the output is verified.

CS3401 | ALGORITHMS
EX. NO :5
IMPLEMENTATION OF BREADTH FIRST SEARCH

AIM:
To write a java program to implement Graph traversal using Breadth First Search.

ALGORITHM:

Step 1: Start
Step 2: Get Size(N) of the vertices of an Graph
Step 3: Intialize AdjList[N][N] = „0‟
Step 4: Get Adjacency List of a graph .
Step 5: Enque the Starting vertex to the queue
Step 6: Mark as Visited
Step 7: Enque All the neighbours of a vertex at the front of the Queue, which is not visited.
Step 8: Mark all the Enqueued vertices as visited.
Step 9: Dequeue and Display the vertex At Front of the Queue.
Step 10: Repeat Step 7 to 10 untill the queue become empty.
Step 11: Stop.

PROGRAM:
import java.util.HashMap;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner get = new Scanner(System.in);
Queue<Character>ch = new LinkedList<>();
HashMap<Character,Boolean>check = new HashMap<>();
HashMap<Character,Integer>index = new HashMap<>();
int size,i,j;
System.out.print("Enter the size of node : ");
size = get.nextInt();
char adjmat[][] = new char[size][size];
for(i=0;i<size;++i) {
for(j=0;j<size;++j){
adjmat[i][j]='0';
}
}
j=0;
for(i=0;i<size;++i){
System.out.printf("Enter node %d with its neighbours(char) eg:A:BCE : ",i+1);
String str[] = get.next().split(":");
adjmat[i][j++]=str[0].charAt(0);

CS3401 | ALGORITHMS
index.put(str[0].charAt(0),i);
if(str.length>1){
for(char c:str[1].toCharArray())
adjmat[i][j++]=c;
}
j=0;
}
System.out.print("Enter the name of starting node to traverse : ");
char st = get.next().charAt(0);
i =index.get(st);
System.out.printf("The Breadth First Traversal is : ");
check.put(adjmat[i][0],true) ;
ch.add(adjmat[i][0]);
while(ch.size()!=0){
if(!check.containsKey(adjmat[i][0]))
{
check.put(adjmat[i][0],true) ;
ch.add(adjmat[i][0]);
}
System.out.print(ch.remove());
for(j=1;((j< size) && (adjmat[i][j]!='0')) ;++j){
if(!check.containsKey(adjmat[i][j]))
{
check.put(adjmat[i][j],true) ;
ch.add(adjmat[i][j]);
}
}
if(ch.size()>0)
i = index.get(ch.peek());
}
}
}

OUTPUT:
Enter the size of node: 6
Enter node 1 with its neighbours(char) eg:A:BCE : A:CE
Enter node 2 with its neighbours(char) eg:A:BCE : B:F
Enter node 3 with its neighbours(char) eg:A:BCE : C:BDF
Enter node 4 with its neighbours(char) eg:A:BCE : D:F
Enter node 5 with its neighbours(char) eg:A:BCE : E:F
Enter node 6 with its neighbours(char) eg:A:BCE : F:
Enter the name of starting node to traverse: A
The Breadth First Traversal is: ACEBDF

RESULT:
Thus the program to implement Graph Traversal Using Breadth First Search is executedsuccessfully and
the output is verified
CS3401 | ALGORITHMS
EX. NO :6
IMPLEMENTATION OF DEPTH FIRST SEARCH

AIM:
To write a java program to implement Graph traversal using Depth First Search.

ALGORITHM:
Step 1: Start
Step 2: Get Size(N) of the vertices of an Graph
Step 3: Intialize AdjList[N][N] = „0‟
Step 4: Get Adjacency List of a graph.
Step 5: Push the starting vertex to the stack.
Step 6: Mark the Pushed Nodes as Visited.
Step 7: Display the vertex.
Step 8: Push the very first neighbour of the vertex at the top of stack.
Step 9: Mark the pushed node as visited
Step 10: IF All the neighbours of an vertex at top, are visited then pop it.
Step 11: Repeat step 7 to 10 utill the stack become empty.
Step 12: Stop.

PROGRAM:
import java.util.HashMap;
import java.util.Stack;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner get = new Scanner(System.in);
boolean visited =true;
Stack<Character> ch = new Stack<>();
HashMap<Character,Boolean>check = new HashMap<>();
HashMap<Character,Integer>index = new HashMap<>();
int size,i,j;
System.out.print("Enter the size of node : ");
size = get.nextInt();
char adjmat[][] = new char[size][size];
for(i=0;i<size;++i){
for(j=0;j<size;++j){
adjmat[i][j]='0';
}
}
j=0;
for(i=0;i<size;++i){
System.out.printf("Enter node %d with its neighbours(char) eg:A:BCE : ",i+1);
String str[] = get.next().split(":");
adjmat[i][j++]=str[0].charAt(0);
index.put(str[0].charAt(0),i);
if(str.length>1){
CS3401 | ALGORITHMS
for(char c:str[1].toCharArray())
adjmat[i][j++]=c;
}
j=0;
}
System.out.print("Enter the starting node name to traverse : ");
char st = get.next().charAt(0);
i =index.get(st);
System.out.printf("The Depth First Traversal is : ");
check.put(adjmat[i][0],true) ;
ch.push(adjmat[i][0]);
System.out.print(adjmat[i][0]);
while(!ch.empty() && check.size()!=size) {
visited =false;
for(j=1;((j<size) && (adjmat[i][j]!='0')) ;++j){
if(!check.containsKey(adjmat[i][j])){
System.out.print(adjmat[i][j]);
check.put(adjmat[i][j],true);
ch.push(adjmat[i][j]);
i = index.get(adjmat[i][j]);
visited = true;
break;
}
}
if(!visited){
i =ch.pop();
if(!ch.empty())
i = index.get(ch.peek());
}
}
}
}

OUTPUT:
Enter the size of node : 8
Enter node 1 with its neighbours(char) eg:A:BCE : A:EBG
Enter node 2 with its neighbours(char) eg:A:BCE : B:AHGFC
Enter node 3 with its neighbours(char) eg:A:BCE : C:BHD
Enter node 4 with its neighbours(char) eg:A:BCE : D:CE
Enter node 5 with its neighbours(char) eg:A:BCE : E:ADF
Enter node 6 with its neighbours(char) eg:A:BCE : F:EB
Enter node 7 with its neighbours(char) eg:A:BCE : G:AB
Enter node 8 with its neighbours(char) eg:A:BCE : H:BC
Enter the starting node name to traverse : A
The Depth First Traversal is : AEDCBHGF

RESULT:
Thus the program to implement Graph Traversal Using Depth First Search is executedsuccessfully and
the output is verified.
CS3401 | ALGORITHMS
EX. NO :7
IMPLEMENTATION OF DIJKSTRA’S ALGORITHM

AIM:
To develop a java program to find the shortest paths from source to other vertices using dijkstra‟s
algorithm.

ALGORITHM:
Step 1: Start
Step 2: Get SIZE (N) of a vertex in a graph and declare Adjmat[N][N].
Step 3: Initialize cost[i] = INFINITY and visited[i] = false , (for all 0<=i <N)
Step 4: Get Adjacency matrix of a graph with source vertex.
Step 5: Set cost[source] = 0 and row = -1 ,count=0.
Step 6: While count < N
Step 6.1: Set MIN = INFINITY , I = 0
Step 6.2: While I < SIZE
Step 6.3.1: IF (!Visited && MIN > cost[I])
Set MIN = cost[I] and row =I
Step 6.3.2: Set I +=1
[END OF WHILE]
Step 6.4: Set Visited[row] = true
Step 6.5: Set I=0
Step 6.6: While I < Size
Step 6.6.1: IF (!Visited && cost(row)+mat[row][i] < row[i])
cost[i] = cost[row]+mat[row][i]
Step 6.6.2: Set I + =1
[END OF WHILE]
Step 6.7: Set count +=1
[END OF WHILE]
Step 7: Display cost
Step 8: Stop.

PROGRAM :
import java.util.Scanner;
public class Main{
public static void Dijkstras(int mat[][],int size,int start){
int min=0,row=0,count =0;
boolean visited[] = new boolean[size];
int cost[] = new int[size];
for(int i=0;i<size;i++)
cost[i] = Integer.MAX_VALUE;
cost[start] =0;
while(count < size){
min = Integer.MAX_VALUE;
for(int i=0;i<size;++i){
if(min> cost[i] && !visited[i]){
row =i;
min = cost[i];
CS3401 | ALGORITHMS
}
}
visited[row] =true;
for(int i=0;i<size;++i){
if(!visited[i] && mat[row][i]>0 &&(cost[row]+ mat[row][i]) < cost[i] )
cost[i] = cost[row]+ mat[row][i] ;
}
++count;
}
min=1;
for(int i : cost)
System.out.printf("The Minimum distance from node %d -> %d is : %d\n",start+1,min++,i );
}
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
System.out.print("Enter the number of vertices : ");
int vertex,start;
vertex= get.nextInt();
int Adjmat [][] = new int[vertex][vertex];
System.out.println("Enter Adjacency Matrix of a graph : ");
for(int i=0;i<vertex;++i)
for(int j=0;j<vertex;++j)
Adjmat[i][j] = get.nextInt();
System.out.print("Enter the source node : ");
start = get.nextInt();
Dijkstras(Adjmat,vertex,start-1);
}
}

OUTPUT:
Enter the number of vertices: 6
Enter Adjacency Matrix of a graph:
0 3 4 -1 -1 -1
3 0 2 2 1 -1
4 2 0 -1 3 -1
-1 3 -1 0 2 1
-1 1 3 2 0 3
-1 -1 -1 1 3 0
Enter the source node : 2
The Minimum distance from node 2 -> 1 is : 3
The Minimum distance from node 2 -> 2 is : 0
The Minimum distance from node 2 -> 3 is : 2
The Minimum distance from node 2 -> 4 is : 2
The Minimum distance from node 2 -> 5 is : 1
The Minimum distance from node 2 -> 6 is : 3

RESULT:
Thus the program to implement dijkstra‟s algorithm was executed successfully and the output is
verified.
CS3401 | ALGORITHMS
EX. NO :8
IMPLEMENTATION OF PRIM’S ALGORITHM

AIM :
To write a java program to find minimum cost spanning tree of a graph using prim‟s algorithm.

ALGORITM :
Step 1: Start
Step 2: Get Size of vertex in a graph and declare Adjmat[N][N]
Step 3: Get Adjacency matrix of an graph with starting vertex
Step 4: Declare Boolean Visited[N] , int Visited_index[N]
Step5: Set Visited[start] = true and Visited_index[0] = start
Step 6: Initialize index=1, j=0, row=0, col=0 , count=1, min=-1
Step 7: While ( count < vertex )
Step 7.1: Set min = INFINITY
Step 7.2: for(int in =0 ; in<=index;++in)
Step 7.2.1: Set i = Visited_index[in];
Step 7.2.2: for (j=0 ; j<vertex ; ++j)
IF mat[i][j]>0 && !Visited[j] && min >mat[i][j]
min = mat[i][j] , row =i , col=j
Step 7.3: Set Visited[col] = true
Step 7.4: Set Visited[index++] = col;
Step 7.5: count+=1 Repeat Step 7 untill all the vertex are visited.
[END OF WHILE]
Step 8: Display Minimum cost.
Step 9: Stop.

PROGRAM:
import java.util.Scanner;
public class Main{
public static void Prims(int vertex, int mat[][],int start){
boolean visited [] = new boolean[vertex];
int visited_index [] = new int [vertex];
int in=0,j,row=0,col=0,count=1,min=-1,sum=0;
visited[start] = true;
visited_index[in++]=start;
System.out.println(" Path weight ");
while(count < vertex){
min=Integer.MAX_VALUE;
for(int i:visited_index){
for(j=0;j<vertex;++j){
if(mat[i][j]>0 && !visited[j]){
if ( min > mat[i][j]){
min = mat[i][j];
row = i;
col =j;
}
CS3401 | ALGORITHMS
else if ( min == mat[i][j] && row > i){
min = mat[i][j];
col = j;
row =i;
}}}}
visited[col] =true;
visited_index[in++] =col;
++count;
sum+=min;
System.out.printf("%d -- %d %d\n",row+1,col+1,min);
}
System.out.print("The minimum cost spanning tree of an given graph is : "+sum);
}
public static void main(String[] args) {
int vertex,i,j;
Scanner get = new Scanner(System.in);
System.out.print("Enter the no of vertex in a graph : ");
vertex = get.nextInt();
int Adjmat[][] = new int[vertex][vertex];
System.out.println("Enter the Adjacency Matrix of an Graph : ");
for(i=0;i<vertex;++i)
for(j=0;j<vertex;++j)
Adjmat[i][j] = get.nextInt();
System.out.print("Enter the starting vertex : ");
int start = get.nextInt();
Prims(vertex,Adjmat,start-1);
}
}

OUTPUT:
Enter the no of vertex in a graph: 6
Enter the Adjacency Matrix of a Graph:
0 3 4 -1 -1 -1
3 0 2 2 1 -1
4 2 0 -1 3 -1
-1 3 -1 0 2 1
-1 1 3 2 0 3
-1 -1 -1 1 3 0
Enter the starting vertex: 2
Path weight
2 -- 5 1
2 -- 3 2
2 -- 4 2
4 -- 6 1
2 -- 1 3
The minimum cost spanning tree of an given graph is : 9
RESULT:
Thus the program to implement prim‟s algorithm to find the cost of minimum spanning tree was
executed successfully and the output is verified.
CS3401 | ALGORITHMS
EX. NO :9
IMPLEMENTATION OF FLOYD’S ALGORITHM

AIM :
To develop a program to implement Floyd‟s algorithm for All-Pairs-Shortest-Path.

ALGORITM :
Step 1: Start
Step 2: Get Size of vertex in a graph and declare costmat[N][N]
Step 3: Get the costmatrix[][] of an graph.
Step 4: Set Distance matrix D[i][j] = costmat[i][j],(for all i,j 0 <=i,j <n)
Step 5: for k =0 to n-1 do
for i=0 to n-1 do
for j=0 to n-1 do
D[i,j] = min(D[i,j] , D[i,k]+D[k,j])
Step 6: Display the Distance Matrix.
Step 7: Stop.

PROGRAM:
import java.util.Scanner;
public class Main{
public static int min(int a,int b){
return (a<b)?a:b;
}
public static void floyd(int mat[][],int n){
int i,j,k;
for(k=0;k<n;k++)
for(i=0;i<n;++i)
for(j=0;j<n;++j)
mat[i][j] = min(mat[i][j], mat[i][k] + mat[k][j]);
}
public static void main(String args[]){
int i,j,n;
Scanner get = new Scanner(System.in);
System.out.print("Enter the number of vertex : ");
n = get.nextInt();
int cost[][] = new int[n][n];
int distance[][] = new int[n][n];
System.out.println("Enter the cost matrix : ");
for(i=0;i<n;++i){
for(j=0;j<n;++j){
cost[i][j] = get.nextInt();
distance[i][j] = cost[i][j];
}
}
floyd(distance,n);

CS3401 | ALGORITHMS
System.out.printf("The final Distance matrix is : \n");
for(i=0;i<n;++i){
for(j=0;j<n;++j)
System.out.print(distance[i][j]+" ");
System.out.println();
}
}
}

OUTPUT:
Enter the number of vertex: 4
Enter the cost matrix:
0 5 99 99
99 0 3 99
99 99 0 4
1 8 99 0
The final Distance matrix is:
0 5 8 12
8 0 3 7
5 10 0 4
1 6 9 0

RESULT:
Thus the program to implement Floyd‟s algorithm for All-Pairs-Shortest-Path was executed successfully
and the output is verified.
CS3401 | ALGORITHMS
EX. NO :10
IMPLEMENTATION OF WARSHALL’S ALGORITHM

AIM :
To develop a java program to implement warshall‟s algorithm to compute the transitive closure
of a Given directed graph.

ALGORITM :
Step 1: Start
Step 2: Get Size of vertex in a graph and declare Adjmat[N][N].
Step 3: Get Adjacency matrix of a graph
Step 4: for k =0 to n-1 do
for i=0 to n-1 do
for j=0 to n-1 do
If Adjmat[i][k]=1 and Adjmat[k][j] =1 then
Adjmat[i][j] = 1
Step 5: Display the transitive closure matrix
Step 6: Stop.

PROGRAM:

import java.util.Scanner;
public class Main{
public static void warshall(int mat[][],int n){
int i,j,k;
for(k=0;k<n;k++)
for(i=0;i<n;++i)
for(j=0;j<n;++j){
if(mat[i][j]==1 ||(mat[i][k]==1 && mat[k][j]==1))
mat[i][j] =1;
}
}
public static void main(String args[]){
int i,j,n;
Scanner get = new Scanner(System.in);
System.out.print("Enter the number of vertex : ");
n = get.nextInt();
int cost[][] = new int[n][n];
int distance[][] = new int[n][n];
System.out.println("Enter the cost matrix : ");
for(i=0;i<n;++i)
for(j=0;j<n;++j){
cost[i][j] = get.nextInt();
distance[i][j] = cost[i][j];
}
warshall(distance,n);
System.out.printf("\nThe transitive closure matrix is : \n");
CS3401 | ALGORITHMS
for(i=0;i<n;++i){
for(j=0;j<n;++j)
System.out.print(distance[i][j]+" ");
System.out.println();
}
}
}

OUTPUT:

Enter the number of vertex: 4


Enter the cost matrix:
0101
0010
0001
0100
The transitive closure matrix is:
0 1 1 1
0 1 1 1
0 1 1 1
0 1 1 1

RESULT:
Thus the program to implement warshall‟s algorithm to compute the transitive closure of a directed
graph is executed successfully and the output is verified.

CS3401 | ALGORITHMS
EX. NO :11 FINDING MAXIMUM AND MINIMUM USING DIVIDE AND
CONQUER

AIM :
To develop a program to find out the maximum and minimum numbers in a given list of n numbers
using the divide and conquer technique.

ALGORITHM:
Step 1: Start
Step 2: Declare a Goble variable called Min and Max
Step 3: Get the size of an array and declare arr[n]
Step 4: Get arr[] inputs
Step 5: Set Min = Max = arr[0]
Step 6: Call minMax(arr, 1, len-1)
Step 7: Display Min and Max

minMax(int arr[] , int l, int r)


Step 8: Set mid = (l+r)/2
Step 9: IF l < r
Step 9.1: minMax(arr,l,mid)
Step 9.2: minMax(arr,mid+1,r)
Step 10: Else
Step 10.1: IF min>arr[l])
Set min =arr[l]
Step 10.2: IF max<arr[l])
Set max =arr[l]
Step 11: Stop.

PROGRAM:
import java.util.Scanner;
public class Main{
public static int min ,max;
public static void minMax(int arr[],int left,int right){
int mid =(int)((left+right)/2);
if(left<right){
minMax(arr,left,mid);
minMax(arr,mid+1,right);
}
else{
if(min>arr[left])
min =arr[left];
if(max<arr[left])
max =arr[left];
}
}
CS3401 | ALGORITHMS
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
System.out.print("Enter the size of an Array : ");
int size = get.nextInt();
int arr[] = new int[size];
System.out.println("Enter the Elements of an array : ");
for(int i=0;i<size;++i)
arr[i]=get.nextInt();
min = max =arr[0];
minMax(arr,1,size-1);
System.out.println("Minimum number is : "+min);
System.out.println("Maximum number is : "+max);
}
}

OUTPUT:
Enter the size of an Array : 8
Enter the Elements of an array :
25182518
Minimum number is : 1
Maximum number is : 8

RESULT:
Thus the program to find out the maximum and minimum numbers in a given list of n numbers using the
divide and conquer technique is executed successfully and the output is verified.
CS3401 | ALGORITHMS
EX. NO:12.A
IMPLEMENTATION OF MERGE SORT

AIM:
To develop a program to implement merge sort.

ALGORITHM:
Step 1: Start
Step 2: Declare size, left, right, mid variable,
Step 3: Get size and declare array[size]
Step 4: Get values to the array
Step 5: Call mergeSort(arr,0,len-1)
Step 6: Display the sorted array
mergeSort(int arr[],int left,int right)
Step 7: Perform merge function.
Step 7.1: Set mid =(left+right)/2
Step 7.2: IF left < right
Step 7.2.1: mid= mergesort(array, left, mid)
Step 7.2.2: mergesort(array, mid+1, right)
Step 7.2.3: merge(array, left, mid, right)
merge(int arr[],int l , int m, int r)
Step 8: Intialize I = l , J =m+1 , K =0
Step 9: Declare temp[r-l+1]
Step 10: While I <= m && J <=r
Step 10.1: IF arr[I] <= arr[J]
Temp[k++] = arr[I++]
Step 10.2: Else:
Temp[k++] =arr[j++]
Step 11: While I<=mid
Temp[k++] = arr[I++]
Step 12: While J<=r
Temp[k++] = arr[J++]
Step 13: Copy the elements in temp array to Arr
Step 14: Stop.

PROGRAM:
import java.util.Scanner;
public class Main{
public static int min ,max;
public static void merge(int arr[],int left,int mid,int right){
int temp[] = new int [right-left+1];
int i=left,j=mid+1,k=0;

while(i<=mid && j<=right){


if(arr[i]<=arr[j])
CS3401 | ALGORITHMS
temp[k++]=arr[i++];
else
temp[k++] =arr[j++];
}
while(i<=mid)
temp[k++]=arr[i++];
while(j<=right)
temp[k++]=arr[j++];
for( i=0;i<k;++i)
arr[left+i]=temp[i];
}
public static void mergeSort(int arr[],int left,int right){
int mid =(int)((left+right)/2.0);
if(left<right){
mergeSort(arr,left,mid);
mergeSort(arr,mid+1,right);
merge(arr,left,mid,right);
}
}
public static void printArr(int arr[]){
for(int i:arr)
System.out.print(i+" ");
}
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
System.out.print("Enter the size of an Array : ");
int size = get.nextInt();
int arr[] = new int[size];
System.out.println("Enter the Elements of an array : ");
for(int i=0;i<size;++i)
arr[i]=get.nextInt();
System.out.print("\nBefore Sort : ");
printArr(arr);
mergeSort(arr,0,size-1);
System.out.print("\nAfter Sort : ");
printArr(arr);
}
}

OUTPUT:
Enter the size of an Array: 8
Enter the Elements of an array:
56211593
Before Sort: 5 6 2 1 1 5 9 3
After Sort: 1 1 2 3 5 5 6 9

RESULT:
Thus the program to implement merge sort is executed successfully and the output is verified.
CS3401 | ALGORITHMS
EX. NO:12.B
IMPLEMENTATION OF QUICK SORT

AIM :
To develop a java program to implement quick sort.

ALGORITHM:
Step 1: Start
Step 2: size and declare arr[size]
Step 3: Get the array elements
Step 4: Call QuickSort(arr, 0, size-1)
Step 5: Display the sorted array
Step 6: Stop.
QuickSort(int arr[] , int low , int high)
Step 1: IF l < h
Step 1.1: Set pivot = Call Partition(arr,l,h)
Step 1.2: Call QuickSort(arr, l ,pivot-1)
Step 1.3 : Call QuickSort(arr,pivot+1,h)
Partition(int arr[], int l, int h)
Step 1: Set pivot = low
Step 2: While low < high
Step 2.1: While low < = high and arr[low] <= arr[pivot]
low = low+1
Step 2.2: While arr[high] > arr[pivot] and low <= high
high = high-1
Step 2.3: IF low < high
Swap (arr[low],arr[high])
Step 3: Repeat Step 2 until low < high
Step 4: Swap (arr[swap],arr[high])
Step 5: return high

PROGRAM:
import java.util.Scanner;
public class Main {
public static int partition(int arr[],int low,int high){
int pivot = low;
int temp;
while( low < high){
while(low <= high && arr[low]<=arr[pivot] ){
++low;
}
while(arr[high]>arr[pivot] && low <= high){
--high;
}
if(low < high){
CS3401 | ALGORITHMS
temp= arr[low];
arr[low]=arr[high];
arr[high]=temp;
}
}
temp =arr[pivot];
arr[pivot] = arr[high];
arr[high] = temp;
return high;
}
public static void quickSort(int arr[],int low,int high){
if(low < high){
int pivot = partition(arr,low,high);
quickSort(arr,low,pivot-1);
quickSort(arr,pivot+1,high);
}
}
public static void printArray(int arr[]){
for(int num:arr)
System.out.print(num+" ");
}
public static void main(String ar[]){
Scanner get = new Scanner(System.in);
int size;
System.out.print("Enter the size of an array : ");
size = get.nextInt();
int arr[] = new int[size];
System.out.print("Enter the array elements: ");
for(int i=0;i<size;++i)
arr[i] = get.nextInt();
System.out.print("\n Before sort : ");
printArray(arr);
quickSort(arr,0,size-1);
System.out.print("\n After sort : ");
printArray(arr);
}
}

OUTPUT:
Enter the size of an array: 7
Enter the array elements: 5 2 3 7 1 5 1
Before sort: 5 2 3 7 1 5 1
After sort: 1 1 2 3 5 5 7

RESULT:
Thus the program to implement quick sort is executed successfully and the output is verified.
CS3401 | ALGORITHMS
EX. NO:13 IMPLEMENTATION OF N QUEENS PROBLEM USING
BACKTRACKING

AIM :
To develop a C program to implement N Queens problem using Backtracking.

ALGORITHM:
Step 1: Start
Step 2: Initialize an empty chessboard of size NxN.
Step 3: Start with the leftmost column and place a queen in the first row of that column.
Step 4: Move to the next column and place a queen in the first row of that column.
Step 5: Repeat step 3 until either all N queens have been placed or it is impossible to place a queen in the
current column without violating the rules of the problem.
Step 6: If all N queens have been placed, print the solution.
Step 7: If it is not possible to place a queen in the current column without violating the rules of the problem,
backtrack to the previous column.
Step 8: Remove the queen from the previous column and move it down one row.
Step 9: Repeat steps 4-7 until all possible configurations have been tried.
Step 10: Stop

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int board[20],count;
int main(){
int n,i,j;
void queen(int row,int n);
printf("Enter number of Queens:\n");
scanf("%d",&n);
queen(1,n);
return 0;
}

void print(int n){


int i,j;
printf("\nSolution %d:\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i){
printf("\n\n%d",i);
for(j=1;j<=n;++j){
if(board[i]==j)
printf("\tQ");
else
CS3401 | ALGORITHMS
printf("\t-");
}
}
}

int place(int row,int column){


int i;
for(i=1;i<=row-1;++i){
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}
return 1;
}

void queen(int row,int n){


int column;
for(column=1;column<=n;++column){
if(place(row,column)){
board[row]=column;
if(row==n)
print(n);
else
queen(row+1,n);
}
}
}

CS3401 | ALGORITHMS
OUTPUT:
Enter number of Queens:
4
Solution 1:
1 2 3 4

1 - Q - -

2 - - - Q

3 Q - - -

4 - - Q -

Solution 2:
1 2 3 4

1 - - Q -

2 Q - - -

3 - - - Q

4 - Q - -

RESULT:
Thus the program to implement N Queens problems using Backtracking is executed successfully and the
output is verified.
CS3401 | ALGORITHMS
EX. NO:14 IMPLEMENTATION OF TRAVELING SALESPERSON PROBLEM
USING APPROXIMATION ALGORITHMS

AIM:
To develop a C++ program to implement traveling salesman problem suing approximation algorithms.

ALGORITHM:
Step 1: Start
Step 2: Constructing the Minimum Spanning Tree.
2.1: Creating a set mstSet that keeps track of vertices already included in MST.
2.2: Assigning a key value to all vertices in the input graph. Initialize all key values as INFINITE.
Assign key value as 0 for the first vertex so that it is picked first.
2.3: [The Loop] While mstSet doesn‟t include all vertices
2.3.1: Pick a vertex u which is not there in mstSet and has minimum key value.(minimum_key())
2.3.2: Include u to mstSet.
2.3.3: Update key value of all adjacent vertices of u. To update the key values, iterate through all
adjacent vertices. For every adjacent vertex v, if weight of edge u-v is less than the previous key
value of v, update the key value as weight of u-v.
Step 3: Getting the preorder or Defth first search traverse.
Step 4: Stop

PROGRAM:
#include <bits/stdc++.h>
using namespace std;
#define V 5
vector<int> final_ans;
int minimum_key(int key[], bool mstSet[]){
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
vector<vector<int>> MST(int parent[], int graph[V][V]){
vector<vector<int>> v;
for (int i = 1; i < V; i++){
vector<int> p;
p.push_back(parent[i]);
p.push_back(i);
v.push_back(p);
p.clear();
}
return v;
}

CS3401 | ALGORITHMS
vector<vector<int>> primMST(int graph[V][V]){
int parent[V];
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++){
int u = minimum_key(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
vector<vector<int>> v;
v = MST(parent, graph);
return v;
}

void DFS(int** edges_list,int num_nodes,int starting_vertex,bool* visited_nodes){


final_ans.push_back(starting_vertex);
visited_nodes[starting_vertex] = true;
for(int i=0;i<num_nodes;i++){
if(i==starting_vertex)
continue;
if(edges_list[starting_vertex][i]==1){
if(visited_nodes[i])
continue;
DFS(edges_list,num_nodes,i,visited_nodes);
}
}
}
int main(){
int graph[V][V] = { { 0, 10, 18, 40, 20 },
{ 10, 0, 35, 15, 12 },
{ 18, 35, 0, 25, 25 },
{ 40, 15, 25, 0, 30 },
{ 20, 13, 25, 30, 0 } };
vector<vector<int>> v;
v = primMST(graph);
int** edges_list = new int*[V];
for(int i=0;i<V;i++){
edges_list[i] = new int[V];
for(int j=0;j<V;j++)
edges_list[i][j] = 0;
}
for(int i=0;i<v.size();i++){
CS3401 | ALGORITHMS
int first_node = v[i][0];
int second_node = v[i][1];
edges_list[first_node][second_node] = 1;
edges_list[second_node][first_node] = 1;
}
bool* visited_nodes = new bool[V];
for(int i=0;i<V;i++){
bool visited_node;
visited_nodes[i] = false;
}
DFS(edges_list,V,0,visited_nodes);
final_ans.push_back(final_ans[0]);
for(int i=0;i<final_ans.size();i++)
cout << final_ans[i] << "-";
return 0;
}

OUTPUT:
0-1-3-4-2-0

RESULT:
Thus the program to implement TSP using approximation algorithms is executed successfully and the
output is verified.
CS3401 | ALGORITHMS
EX. NO:15 IMPLEMENTATION OF FINDING THE KTH SMALLEST NUMBER
USING RANDOMIZED ALGORITHMS

AIM:
To develop a C++ program to implement finding the kth smallest number using randomized algorithms.

ALGORITHM:
Step 1: Start
Step 2: Apply quicksort algorithm on the input array.
Step 3: During quick sort, select a pivot element randomly from the range of the array from low to high and
move it to its correct position.
Step 4: If index of pivot is equal to K the return the value.
Step 5: Else if the index of pivot is greater than K, then scan for the left subarray recursively, else scan for
the right subarray recursively.
Step 5: Repeat this process until the element at index K is not found.
Step 6: Stop

PROGRAM:
#include <iostream>
using namespace std;
#define infinity 9999
int partition(int[],int,int);
int count;
void swap(int*,int*);
int kthSmallest(int A[], int left, int right, int K){
if (K>0 && K<=(right-left+1)){
int pos=partition(A, left, right);
if(pos-left==K-1)
return A[pos];
if(pos-left>K-1)
return kthSmallest(A,left,pos-1,K);
return kthSmallest(A,pos+1,right,(K-pos+left-1));
}
return infinity;
}

int partition(int A[],int l,int r){


int range=(r-l)+1;
int rand_index=(rand()%range)+l;
swap(&A[rand_index],&A[r]);
int x=A[r],i=l;
for(int j = l;j<=r-1;j++){
if (A[j] <= x){
swap(&A[i],&A[j]);
i=i+1;
CS3401 | ALGORITHMS
}
}
swap(&A[i],&A[r]);
return i;
}
void swap(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}

int main(){
int arr[]={154,25,12,365,84};
int N= sizeof(arr)/sizeof(arr[0]);
int K;
cout<<"Enter the value of K:\n";
cin>>K;
cout<< "Kth Smallest element is:";
cout<<kthSmallest(arr,0,N-1,K);
return 0;
}

OUTPUT:
Enter the value of K:
2
Kth Smallest element is: 25

RESULT:
Thus the program to implement finding the kth smallest number using randomized algorithms is
executed successfully and the output is verified.

CS3401 | ALGORITHMS
CONTENT BEYOND SYLLABUS

CS3401 | ALGORITHMS
EX. NO:16
IMPLEMENTATION OF EGG DROPPING PUZZLE

AIM:
To solve Egg dropping puzzle using appropriate algorithmic design technique.

Problem Description:
The following is a description of the instance of this famous puzzle involving N = 2 eggs and a building
with K = 36 floors.
Suppose that we wish to know which stories in a 36-story building are safe to drop eggs from, and which
will cause the eggs to break on landing. We make a few assumptions:
 An egg that survives a fall can be used again.
 A broken egg must be discarded.
 The effect of a fall is the same for all eggs.
 If an egg breaks when dropped, then it would break if dropped from a higher floor.
 If an egg survives a fall then it would survive a shorter fall.
 It is not ruled out that the first-floor windows break eggs, nor is it ruled out that the 36th-floor does
not cause an egg to break.

If only one egg is available and we wish to be sure of obtaining the right result, the experiment can be
carried out in only one way. Drop the egg from the first-floor window; if it survives, drop it from the
second-floor window. Continue upward until it breaks. In the worst case, this method may require 36
droppings. Suppose 2 eggs are available. What is the least number of egg droppings that are gua ranteed to
work in all cases?
The problem is not actually to find the critical floor, but merely to decide floors from which eggs should be
dropped so that the total number of trials is minimized.
DISCUSSION:
This problem can be solved using many approaches:
1. Egg Dropping Puzzle using Recursion:
 Time Complexity: As there is a case of overlapping sub-problems the time complexity is
exponential.
 Auxiliary Space: O(1). As there was no use of any data structure for storing values.
2. Egg Dropping Puzzle using Dynamic Programming:
 Time Complexity: O(N * K2). As we use a nested for loop „k^2‟ times for each egg.
 Auxiliary Space: O(N * K). A 2-D array of size „n*k‟ is used for storing elements.

We need to choose the algorithmic design technique which has better time efficiency.

CS3401 | ALGORITHMS
PROGRAM: (Implementation using Dynamic Programming)
import java.util.*;
public class Main {
static int minTrials(int n, int k){
int dp[][] = new int[k + 1][n + 1];
int m = 0;
while (dp[m][n] < k){
m++;
for (int x = 1; x <= n; x++){
dp[m][x] = 1 + dp[m - 1][x - 1] + dp[m - 1][x];
}
}
return m;
}
public static void main(String[] args){
int n = 2, k = 36;
System.out.println("Minimum number of trials in worst case with " + n + " eggs and "+ k + " floors is "+
minTrials(2, 36));
}
}

OUTPUT:
Minimum number of trials in worst case with 2 eggs and 36 floors is 8

RESULT:
Thus the program to implement finding Egg dropping puzzle problem using dynamic programming is
executed successfully and the output is verified.
CS3401 | ALGORITHMS
EX. NO:17
IMPLEMENTATION OF JOB SEQUENCING PROBLEM

AIM:
To solve Job Sequencing Problem using appropriate algorithmic design technique.

Problem Description:
Given an array of jobs where every job has a deadline and associated profit if the job is finished before the
deadline. It is also given that every job takes a single unit of time, so the minimum possible deadline for any
job is 1. Maximize the total profit if only one job can be scheduled at a time.
Example:
Input:
Five Jobs with following deadlines and profits.
JobID Deadline Profit
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output: Maximum profit sequence of jobs: c, a, e
DISCUSSION:
This problem can be solved using many approaches:
1. Naive Approach :
Generate all subsets of a given set of jobs and check individual subsets for the feasibility of jobs in that
subset. Keep track of maximum profit among all feasible subsets.
2. Greedy Approach:
Greedily choose the jobs with maximum profit first, by sorting the jobs in decreasing order of their
profit. This would help to maximize the total profit as choosing the job with maximum profit for every
time slot will eventually maximize the total profit.
Follow the given steps to solve the problem:
 Sort all jobs in decreasing order of profit.
 Iterate on jobs in decreasing order of profit. For each job, do the following :
 Find a time slot i, such that slot is empty and i < deadline and i is greatest.
Put the job in this slot and mark this slot filled.
 If no such i exists, then ignore the job.
Time Complexity: O(N2)
Auxiliary Space: O(N)
3. Priority-Queue:
Steps to solve the problem:
 Sort the jobs based on their deadlines.
 Iterate from the end and calculate the available slots between every two consecutive
deadlines. Insert the profit, deadline, and job ID of ith job in the max heap.
 While the slots are available and there are jobs left in the max heap, include the job ID with
maximum profit and deadline in the result.
 Sort the result array based on their deadlines.
Time Complexity: O(N log N)
Auxiliary Space: O(N)

CS3401 | ALGORITHMS
PROGRAM:
import java.util.*;
class Job{
char id;
int deadline, profit;
public Job() {}
public Job(char id, int deadline, int profit){
this.id = id;
this.deadline = deadline;
this.profit = profit;
}
void printJobScheduling(ArrayList<Job> arr, int t){
int n = arr.size();
Collections.sort(arr,(a, b) -> b.profit - a.profit);
boolean result[] = new boolean[t];
char job[] = new char[t];
for (int i = 0; i < n; i++) {
for (int j
= Math.min(t - 1, arr.get(i).deadline - 1);
j >= 0; j--) {
if (result[j] == false) {
result[j] = true;
job[j] = arr.get(i).id;
break;
}
}
}
for (char jb : job)
System.out.print(jb + " ");
System.out.println();
}
public static void main(String args[]){
ArrayList<Job> arr = new ArrayList<Job>();
arr.add(new Job('a', 2, 100));
arr.add(new Job('b', 1, 19));
arr.add(new Job('c', 2, 27));
arr.add(new Job('d', 1, 25));
arr.add(new Job('e', 3, 15));
System.out.println("Following is maximum profit sequence of jobs");
Job job = new Job();
job.printJobScheduling(arr, 3);
}
}

OUTPUT:
Following is maximum profit sequence of jobs
cae

RESULT:
Thus the program to implement Job Sequencing problem using Greedy approach is executed
successfully and the output is verified.
CS3401 | ALGORITHMS
VIVA VOCE

CS3401 | ALGORITHMS
1. Define Algorithm.
2. Define Notion of Algorithm.
3. What is recursive algorithm?
4. List the features of efficient algorithm?
5. What do you mean by sorting problem?
6. What is a basic operation?
7. Define order of growth and compare the order of growth of n (n-1)/2 and n2.
8. How to measure the algorithm‟s efficiency and algorithm‟s running time?
9. What are the different types of time complexity?
10. What is amortized efficiency?
11. What do meant by “Worst case efficiency” of an algorithm?
12. Differentiate Time Efficiency and Space Efficiency.
13. Write down the properties of asymptotic notations.
14. What is Big „Oh‟ Notation?
15. What is a recurrence equation?
16. Classify big oh (O), Big omega (Ω) and big theta (Ө) notations.
17. Write an algorithm using recursive function to find the sum of n numbers.
18. Define Linear Search
19. Define Binary Search.
20. What is the Time complexity for Binary Search?
21. Differentiate linear and Binary Search
22. List out some pattern matching algorithms.
23. Compare naïve string matching with Rabin Karp.
24. Compare Rabin Karp with Knuth-Morris-Pratt algorithm.
25. Define Insertion sort. Specify the time and space efficiency.
26. Write the advantages of insertion sort.
27. Define Heap Sort.
28. Write the efficiency of heap sort algorithm.
29. Define BFS.
30. Define DFS.
31. Define the minimum spanning tree problem.
32. Define Dijkstra‟s algorithm.
33. State Prim‟s algorithm.
34. Define kruskal‟s algorithm?
35. Differentiate Prim‟s and Kruskal‟s algorithm.
36. State Floyd‟s algorithm.
37. Define transitive closure of a directed graph.
38. Analyze the Time complexity for Floyd‟s algorithm
39. State warshall‟s algorithm.
40. Define divide and conquer technique.
41. Define Merge sort.
42. Analyze the Time efficiency and Drawback of Merge sort algorithm.
43. Define Quicksort.
44. List out the Advantages in Quick Sort.
45. Analyze the Time complexity for Quick sort algorithm.
46. Is Merge Sort and Quick Sort as table sorting algorithm?
47. Is insertion sort better than the merge sort?
48. What do you mean by dynamic programming?
CS3401 | ALGORITHMS
49. Show the general procedure of dynamic programming.
50. What are the drawbacks of dynamic programming?
51. What is greedy method?
52. Illustrate any two characteristics of Greedy Algorithm?
53. What are the differences between dynamic programming and divide and conquer approaches?
54. Compare Greedy method and Dynamic programming.
55. List the advantage of greedy algorithm.
56. Compare Feasible and Optimal solution.
57. Illustrate the general principle of greedy algorithm.
58. List the characteristics of Greedy algorithm.
59. Define Backtracking.
60. What is solution state space tree in backtracking?
61. Summarize the requirements that are needed for performing Backtracking?
62. List the factors that influence the efficiency of the backtracking algorithm?
63. Compare backtracking and branch bound techniques.
64. Illustrate N Queens problem.
65. Define Traveling Salesman Problem.
66. What are tractable and non-tractable problems?
67. Define „P‟and „NP‟ problems.
68. Compare NP- hard and Np-complete problems?
69. Show the time complexity and space complexity of traveling salesperson problem.
70. What is meant by approximation algorithm?
71. List the features of Approximation algorithms.
72. What is Absolute approximation?
73. What is Relative approximation?
74. What is randomized algorithm?
75. List the features of Randomized Algorithms.

CS3401 | ALGORITHMS

You might also like