0% found this document useful (0 votes)
114 views51 pages

ADS Record Final PDF

The document describes an algorithm for implementing Dijkstra's algorithm to find the shortest path between vertices in a graph. It outlines the steps of the algorithm which are to initialize distances and predecessors, add all nodes to a priority queue sorted by distance, repeatedly extract the node with the smallest distance and update distances and predecessors of neighboring nodes, and return the distances and predecessors once the priority queue is empty. It then provides a Java program implementation of the algorithm using classes for vertices and edges to represent the graph and a priority queue.

Uploaded by

Arun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views51 pages

ADS Record Final PDF

The document describes an algorithm for implementing Dijkstra's algorithm to find the shortest path between vertices in a graph. It outlines the steps of the algorithm which are to initialize distances and predecessors, add all nodes to a priority queue sorted by distance, repeatedly extract the node with the smallest distance and update distances and predecessors of neighboring nodes, and return the distances and predecessors once the priority queue is empty. It then provides a Java program implementation of the algorithm using classes for vertices and edges to represent the graph and a priority queue.

Uploaded by

Arun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Ex.

No :

BREADTH FIRST SEARCH

DATE :

AIM
To write a java program to implement graph searching algorithm using Breadth First Search.
ALGORITHM
begin
visited =
notvisited ={s}
d(s) = 0, (s) = null
loop
<loop-invariant>:
exit when notvisited =
let u be the node in the front of the queue notvisited
for each v connected to u
if v has not previously been visited then
addv to notvisited
d(v) =d(u)+1
(v) =u
end if
end for
move u from notvisited to visited
end loop
(for unfound v, d(v) = )
return<d, >

end

PROGRAM
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFS
{
private Queue<Integer> queue;
public BFS()
{
queue = new LinkedList<Integer>();
}
public void bfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int[] visited = new int[number_of_nodes + 1];
int i, element;
visited[source] = 1;
queue.add(source);
while (!queue.isEmpty())
{
element = queue.remove();
i = element;
System.out.print(i + "\t");
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)

{
queue.add(i);
visited[i] = 1;
}
i++;
}
}
}
public static void main(String... arg)
{
int number_no_nodes, source;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_no_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_no_nodes + 1]
[number_no_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_no_nodes; i++)
for (int j = 1; j <= number_no_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
System.out.println("The BFS traversal of the graph is ");
BFS bfs = new BFS();

bfs.bfs(adjacency_matrix, source);
}
catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scanner.close();
}
}
OUTPUT
Enter the number of nodes in the graph
4
Enter the adjacency matrix
0110
0001
0001
0000
Enter the source for the graph
1
The BFS traversal of the graph is
1

RESULT
Thus the java program to implement bipartite is executed and the output is verified.

Ex. No :
DEPTH FIRST SEARCH

DATE :
AIM

To write a java program to implement graph searching algorithm using Depth First Search.
ALGORITHM
begin foundHandled =path
foundNotHandled ={<s,0 >}
time= 0 % Used fortime stamping.
loop
exit when foundNotHandled =path
pop<u,i> off the stack foundNotHandled
if u has an (i+1)st edge<u, v>
push<u,i +1>onto foundNotHandled
if v has not previously been found then
(v) =u ; <u, v> is a tree edge
push<v,0 > onto foundNotHandled
s(v) =time; time=time+1
else if v has been found but not completely handled then <u, v> is a back edge
else (v has been completely handled) <u, v> is a forward or cross edge
end if
else move u to foundHandled f(v) =time; time=time+1
end if
end loop
return foundHandled

end

PROGRAM
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class DFS{
private Stack<Integer> stack;
public DFS()
{
stack = new Stack<Integer>();
}
public void dfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
System.out.print(element + "\t");
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
{
stack.push(i);
visited[i] = 1;
element = i;
i = 1;

System.out.print(element + "\t");
continue;
}
i++;
}
stack.pop();
}
}
public static void main(String...arg)
{
int number_of_nodes, source;
Scanner scanner = null;
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new int[number_of_nodes + 1]
[number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
System.out.println("The DFS Traversal for the graph is given by ");
DFS dfs = new DFS();
dfs.dfs(adjacency_matrix, source);
}
Catch(InputMismatchException inputMismatch)
{

System.out.println("Wrong Input format");


}
scanner.close();
}

OUTPUT
Enter the number of nodes in the graph
4
Enter the adjacency matrix
0110
0001
0001
0000
Enter the source for the graph
1
The DFS Traversal for the graph is given by
1

RESULT
Thus the java program for implementing Depth first search using graph search algorithm is
executed and output is verified.

Ex. No :
DATE :

TRAVELLING SALESMAN PROBLEM

AIM
To write a java program to find source to all nodes using travelling salesman problem.
ALGORITHM
Number of cities n and array of costs c(i,j) i,j=1,..n (We begin from city number 1)

Vector of cities and total cost.


(* starting values *)
C=0
cost=0
visits=0
e=1 (*e=pointer of the visited city)
(* determination of round and cost)
for r=1 to n-1 do
choose of pointer j with
minimum=c(e,j)=min{c(e,k);visits(k)=0 and k=1,..,n}
cost=cost+minimum
e=j
C(r)=j
end r-loop
C(n)=1
cost=cost+c(e,1)

PROGRAM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
class FlightInfo
{
String from;
String to;
int distance;
boolean skip;
FlightInfo(String f, String t, int d)
{
from = f;
to = t;
distance = d;
skip = false;
}
}
public class Hill
{
final int MAX = 100;
FlightInfo flights[] = new FlightInfo[MAX];
int numFlights = 0; // number of entries in flight array
Stack btStack = new Stack(); // backtrack stack
public static void main(String args[])
{
String to, from;
Hill ob = new Hill();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ob.setup();
try
{
System.out.print("From? ");

from = br.readLine();
System.out.print("To? ");
to = br.readLine();
ob.isflight(from, to);
if (ob.btStack.size() != 0)
ob.route(to);
}
catch (IOException exc)
{
System.out.println("Error on input.");
}
}
void setup()
{
addFlight("Chennai", "Hyderabad", 900);
addFlight("Hyderabad", "Mumbai", 1000);
addFlight("Chennai", "Kolkatta", 500);
addFlight("Chennai", "Mumbai", 1800);
addFlight("Kolkatta", "Bangalore", 1700);
addFlight("Kolkatta", "New Delhi", 2500);
addFlight("Kolkatta", "Hyderabad", 500);
addFlight("Mumbai", "Trivandrum", 1000);
addFlight("Mumbai", "Cochin", 1000);
addFlight("Cochin", "New Delhi", 1500);
addFlight("Mumbai", "New Delhi", 1000);
}
void addFlight(String from, String to, int dist)
{
if (numFlights < MAX)
{
flights[numFlights] = new FlightInfo(from, to, dist);
numFlights++;
}
else
System.out.println("Flight database full.\n");
}

void route(String to)


{
Stack rev = new Stack();
int dist = 0;
FlightInfo f;
int num = btStack.size();
for (int i = 0; i < num; i++)
rev.push(btStack.pop());
for (int i = 0; i < num; i++)
{
f = (FlightInfo) rev.pop();
System.out.print(f.from + " to ");
dist += f.distance;
}
System.out.println(to);
System.out.println("Distance is " + dist);
}
int match(String from, String to)
{
for (int i = numFlights - 1; i > -1; i--)
{
if (flights[i].from.equals(from) && flights[i].to.equals(to)
&& !flights[i].skip)
{
flights[i].skip = true;
return flights[i].distance;
}
}
return 0;
}
FlightInfo find(String from)
{
int pos = -1;
int dist = 0;
for (int i = 0; i < numFlights; i++)
{
if (flights[i].from.equals(from) && !flights[i].skip)

{
if (flights[i].distance > dist)
{
pos = i;
dist = flights[i].distance;
}
}
}
if (pos != -1)
{
flights[pos].skip = true;
FlightInfo f = new FlightInfo(flights[pos].from, flights[pos].to,
flights[pos].distance);
return f;
}
return null;
}void isflight(String from, String to)
{
int dist;
FlightInfo f = null;
dist = match(from, to);
if (dist != 0)
{
btStack.push(new FlightInfo(from, to, dist));
return;
}
if (f != null)
{
btStack.push(new FlightInfo(from, to, f.distance));
isflight(f.to, to);
}
else if (btStack.size() > 0)
{
f = (FlightInfo) btStack.pop();
isflight(f.from, f.to);
}
}}

OUTPUT
From? Chennai
To? Mumbai
Chennai to Mumbai
Distance is 1800

RESULT
Thus the java program to implement Travelling Salesman Problem is executed and the output is
verified.

Ex. No :

DYNAMIC PROGRAMMING DESIGN TECHNIQUE


-DIJIKSTRAS ALGORITHM

DATE :

AIM
To write a program
to find
the shortest path
between
the vertices using
Dijikstra's algorithm.
SHORTEST
PATH
BETWEEN
THE
VERTICES
USING
DIJIKSTRA'S ALGORITHM
ALGORITHM
begin
SHORTEST

PATH BETWEEN THE VERTICES USING


DIJIKSTRA'S
ALGORITHM
d(s) = 0, (s) = null
for other v, d(v)
=and (v)
=nil
SHORTEST
PATH
BETWEEN
THE VERTICES USING
DIJIKSTRA'S
ALGORITHM
handled =
notHandled =priority queue containing all nodes. Priorities given by d(v).
loop
<loop-invariant>:
exit when notHandled =
let u be a node from notHandled with smallest d(u)
for eachv connected to u
foundPathLength =d(u)+w<u,v>
if d(v) > foundPathLength then
d(v) = foundPathLength ; (v) =u
end if
end for
move u from notHandled to handled
end loop
return<d, >

end

PROGRAM
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable<Vertex>{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName)
{
name = argName;
}
public String toString()
{
return name;
}
public int compareTo(Vertex other)
{
return Double.compare(minDistance, other.minDistance);
}
}
class Edge
{
public final Vertex target;
public final double weight;

public Edge(Vertex argTarget, double argWeight)


{
target = argTarget;
weight = argWeight;
}
}
public class Dijkstra
{
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty())
{
Vertex u = vertexQueue.poll();
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance)
{
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);

}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target)
{
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String[] args)
{
Vertex v0 = new Vertex("A");
Vertex v1 = new Vertex("B");
Vertex v2 = new Vertex("C");
Vertex v3 = new Vertex("D");
Vertex v4 = new Vertex("E");
Vertex v5 = new Vertex("F");
Vertex v6 = new Vertex("G");
v0.adjacencies = new Edge[]{new Edge(v1, 5), new Edge(v6, 10)};
v1.adjacencies = new Edge[]{new Edge(v2, 3), new Edge(v0, 5),
new Edge(v3, 1)};
v2.adjacencies = new Edge[]{new Edge(v3, 2), new Edge(v1, 3),
new Edge(v5, 4), new Edge(v6, 8)};
v3.adjacencies = new Edge[]{new Edge(v4, 10), new Edge(v2, 2)};

v4.adjacencies = new Edge[]{new Edge(v5, 6), new Edge(v3, 10)};


v5.adjacencies = new Edge[]{new Edge(v6, 9), new Edge(v4, 6),
new Edge(v2, 4)};
v6.adjacencies = new Edge[]{new Edge(v0, 10), new Edge(v5, 9),
new Edge(v2, 8)};
Vertex[] vertices = { v0, v1, v2, v3, v4, v5, v6 };
computePaths(v0);
for (Vertex v : vertices)
{
System.out.println("Distance to " + v + ": " + v.minDistance);
List<Vertex> path = getShortestPathTo(v);
System.out.println("Path: " + path);
}
}
}

OUTPUT
Distance to A: 0.0
Path: [A]
Distance to B: 5.0
Path: [A, B]
Distance to C: 8.0
Path: [A, B, C]
Distance to D: 6.0
Path: [A, B, D]
Distance to E: 16.0
Path: [A, B, D, E]
Distance to F: 12.0
Path: [A, B, C, F]
Distance to G: 10.0
Path: [A, G]

RESULT
Thus the java program to implement depth first search is executed and the output is verified.

Ex. No :

DYNAMIC PROGRAMMING DESIGN TECHNIQUE


-KNAPSACK PROBLEM

DATE :

AIM
To write a program
to implement
knapsack
problem
SHORTEST
PATH
BETWEEN
THE
VERTICES USING
DIJIKSTRA'S ALGORITHM
ALGORITHM
knapsack(i,j)
SHORTEST

PATH BETWEEN THE VERTICES USING


begin
DIJIKSTRA'S ALGORITHM
if V[i,j]<0
SHORTEST
PATH BETWEEN THE VERTICES USING
if j<Weights[i]
DIJIKSTRA'S
ALGORITHM
value<- knapsack(i-1,j)
else
value<-max(knapsack(i-1,j),values[i]+knapsack(i-1,j-Weights[i]))
end if
V[i,j]<-value
return V[i,j]
end if
end

PROGRAM
import java.io.*;
class knapsack10
{
public static void main(String args[]) throws IOException
{
int capacity,n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println ("\n Enter the number of items u want to enter:");
n= Integer.parseInt(br.readLine());
float p[]=new float[n+1];
float x[]=new float[n+1];
int i,j,k,w;
int WEIGHT[]=new int[n+1],PROFIT[]=new int[n+1];
WEIGHT[0]=0;
PROFIT[0]=0;
for(i=1;i<=n;i++)
{
System.out.println ("\n Enter the weight and profit of "+i+" item ");
WEIGHT[i]= Integer.parseInt(br.readLine());
PROFIT[i]= Integer.parseInt(br.readLine());
p[i]=0;
x[i]=0;
}
System.out.println ("\n Enter the capacity of the knapsack : ");
capacity = Integer.parseInt(br.readLine());
float c[][]=new float [n+1][capacity+1];

for(i=0;i<=n;i++)
for(j=0;j<=capacity;j++)
c[i][j] = 0;
for(i=1;i<=n;i++)
for(w=1;w<=capacity;w++)
if(WEIGHT[i]<=w)
{
if ((PROFIT[i]+c[i-1][w-WEIGHT[i]])>c[i-1][w])
{
c[i][w] = PROFIT[i] + c[i-1][w-WEIGHT[i]];
p[i] = 1;
}
else
{
c[i][w]=c[i-1][w];
p[i] = 0;
}
}
else
{
c[i][w]=c[i-1][w];
p[i] = 0;
}
float temp=0;
int t=0;
for(j=1;j<=capacity;j++)
{

temp = c[n-1][j]-c[n-1][j-1];
for(i=1;i<n;i++)
if(temp==PROFIT[i])
t=i;
x[t] = 1; }
for(j=0;j<=n;j++)
System.out.println (j+"

"+x[j] );

System.out.println ("The profit obtained is "+c[n][capacity]);


}
}

OUTPUT
Enter the number of items u want to enter: 4
Enter the weight and profit of 1 item 3 10
Enter the weight and profit of 2 item 8 4
Enter the weight and profit of 3 item 9 9
Enter the weight and profit of 4 item 8 11
Enter the capacity of the knapsack : 20
0

1.0

1.0

1.0

0.0

0.0

The profit obtained is 30.0

RESULT
Thus the java program to implement knapsack is executed and the output is verified.

Ex. No :
6
DATE :
PROBLEM

BACKTRACKING ALGORITHM USING N-QUEENS

AIM
To write a program to implement backtracking algorithm using N-Queens problem.
ALGORITHM
Queens (C, n,r)
begin
if(r =n ) then
if( C is legal ) then optSol = C & optCost = 1 else optCost = 0
return <optSol, optCost>
else
loop k = 1...n
C'_ = C < r +1, k>
<optSolk, optCostk>=Queens_C_, n,r +1>
end for
kmax =a k that maximizes optCostk,
optSol = optSolkmax
optCost = optCostkmax
return<optSol, optCost>
end if
end

PROGRAM
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Queens
{
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n])
return false; // same column
if ((q[i] - q[n]) == (n - i))
return false; // same major diagonal
if ((q[n] - q[i]) == (n - i))
return false; // same minor diagonal
}
return true;
}
public static void printQueens(int[] q)
{
int N = q.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (q[i] == j)
System.out.print("Q ");
else
System.out.print("* ");
}
System.out.println();
}

System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
{
int N = q.length;
if (n == N)
printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n))
enumerate(q, n+1);
}
}
}
public static void main(String[] args)
{
int N;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Queens");
N = in.nextInt();
enumerate(N);
}
}

OUTPUT
Enter the number of Queens 4
*Q**
***Q
Q***
**Q*
**Q*
Q***
***Q
*Q**

RESULT
Thus the java program to implement n-queens problem is executed and the output is verified.

Ex. No :
6
DATE :

PRODUCER CONSUMER PROBLEM

AIM
To write a program to implement locking and synchronization mechanism using producer
consumer problem.
ALGORITHM
int count = 0;
Producer()
while (TRUE)
produce item();
if (count == MAX SIZE) sleep();
enter item();
count = count + 1;
if (count == 1) wakeup(Consumer);
Consumer()
while(TRUE)
if (count == 0) sleep();
remove item();
count = count - 1;
if (count == MAX SIZE - 1) wakeup(Producer);
consume item();

PROGRAM
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumer
{
public static void main(String args[])
{
Vector sharedQueue = new Vector();
int size = 4,i=0;
System.out.println("\n\t\tImplementation of Producer Consumer Problem\n");
Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer");
Thread consThread = new Thread(new Consumer(sharedQueue, size), "Consumer");
prodThread.start();
consThread.start();
}
}
class Producer implements Runnable
{
private final Vector sharedQueue;
private final int SIZE;
public Producer(Vector sharedQueue, int size)
{
this.sharedQueue = sharedQueue;
this.SIZE = size;
}
public void run()

{
for (int i = 0; i < 10; i++)
{
System.out.println("Produced: " + i);
try
{
produce(i);
}
catch (InterruptedException ex)
{
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
private void produce(int i) throws InterruptedException
{
while (sharedQueue.size() == SIZE)
{
synchronized (sharedQueue)
{
System.out.println("Queue is full " + Thread.currentThread().getName()
+ " is waiting , size: " + sharedQueue.size());
sharedQueue.wait();
}
}
synchronized (sharedQueue)

{
sharedQueue.add(i);
sharedQueue.notifyAll();
}
}
}
class Consumer implements Runnable
{
private final Vector sharedQueue;
private final int SIZE;
int i=0;
public Consumer(Vector sharedQueue, int size)
{
this.sharedQueue = sharedQueue;
this.SIZE = size;
}
public void run()
{
int i=0;
while (i<10) {i++;
try
{
System.out.println("Consumed: " + consume());
Thread.sleep(10);
}
catch (InterruptedException ex)
{

Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
System.out.println("Queue is empty Now");
}
private int consume() throws InterruptedException
{
while (sharedQueue.isEmpty())
{
synchronized (sharedQueue)
{
System.out.println("Queue is empty " + Thread.currentThread().getName()
+ " is waiting , size: " + sharedQueue.size());
sharedQueue.wait();
}
}
synchronized (sharedQueue)
{
sharedQueue.notifyAll();
return (Integer) sharedQueue.remove(0);
}
}

OUTPUT
Implementation of Producer Consumer Problem
Produced: 0
Produced: 1
Produced: 2
Produced: 3
Consumed: 0
Produced: 4
Produced: 5
Queue is full Producer is waiting , size: 4
Consumed: 1
Produced: 6
Queue is full Producer is waiting , size: 4
Consumed: 2
Produced: 7
Queue is full Producer is waiting , size: 4
Consumed: 3
Produced: 8
Queue is full Producer is waiting , size: 4
Consumed: 4
Produced: 9
Queue is full Producer is waiting , size: 4
Consumed: 5
Consumed: 6
Consumed: 7
Consumed: 8
Consumed: 9
Queue is empty Now
RESULT
Thus the java program to implement Producer Consumer problem is executed and the output is
verified.

Ex. No :
6
DATE :

SYNCHRONIZATION OF QUEUE

AIM
To write a java program to implement the synchronization of queue.

ALGORITHM
STEP 1: Include all header files
STEP 2: Using main function create object to the class
STEP 3: Create a new Thread A and B
STEP 4: Using this keyword call the current thread
STEP 5: Execute the program and display the output.

PROGRAM
import java.util.concurrent.locks.*;
class LockDemo
{
public static void main(String args[])
{

ReentrantLock lock=new ReentrantLock();


new LockThread(lock,"A");
new LockThread(lock,"B");

}}
class Shared
{
static int count=0;
}
class LockThread implements Runnable
{
String name;
ReentrantLock lock;
LockThread(ReentrantLock lk,String n)
{
lock=lk;
name=n;
new Thread(this).start();
}
public void run()
{
System.out.println("Starting "+name);
try
{
System.out.println(name+"is waiting to lock count");
lock.lock();
System.out.println(name+"is locking count");
Shared.count++;

System.out.println(name+":"+Shared.count);
System.out.println(name+"is sleeping");
Thread.sleep(1000);
}
catch(InterruptedException exc)
{
System.out.println(exc);
}

finally

{
System.out.println(name+"is unlocking count");
lock.unlock();
}
}}
OUTPUT
Starting A
A is waiting to lock count
Starting B
A is locking count
B is waiting to lock count
A: 1
A is sleeping
A is unlocking count
B is locking count
B: 2
B is sleeping
B is unlocking count

RESULT
Thus the java program to implement concurrent queue is executed and the output is verified.

Ex. No :
6
DATE :

IMPLEMENTATION OF SEMAPHORES
INVOLVING CONCURRENCY

AIM
To write a java program for the implementation of semaphores involving concurrency.
ALGORITHM
STEP 1 : Start the program.
STEP 2 : Create the object sem of semaphore(1).
STEP 3 : Shared class count variable is declared to 0.
STEP 4 : Initially thread A invokes IncThread call where the thread gets started.
STEP 5 : Thread A is waiting for premit is displayed.
STEP 6 : Run for loop till counts less than 5 and increment the shared.count.
STEP 7 : Once the loop exits thread A releases the permit is displayed and semaphore
is released.
STEP 8 : After thread A processes thread B invokes DecThread call where the thread
gets started.
STEP 9 : Thread B and is waiting for premit is displayed.
STEP 10 : Once the semaphore is aquired, thread B gets the permit is displayed.
STEP 11 : Run for loop till counts less than 5 and decrement the shared.count.
STEP 12 : Once the loop exits thread B releases the permit is displayed and semaphore
is released
STEP 13 : End the program.

PROGRAM
import java.util.concurrent.*;
class SemDemo
{
public static void main (String args[])
{
Semaphore sem=new Semaphore(1);
new IncThread(sem ,"A");
new DecThread(sem ,"B");
}}
class Shared
{
static int count=0;
}
class IncThread implements Runnable
{
String name;
Semaphore sem;
IncThread(Semaphore s,String n)
{
sem= s;
name= n;
new Thread(this).start();
}
public void run()
{
System.out.println("Starting " + name);
try
{
System.out.println(name + "is waiting for a permit.");
for(int i=0;i<5;i++)
{
Shared.count++;

System.out.println(name + ": "+ Shared.count);


Thread.sleep(10);
}

catch(InterruptedException exc)
{

System.out.println(exc);

System.out.println(name + " releases the permit.");


sem.release();
}}
class DecThread implements Runnable
{
String name;
Semaphore sem;
DecThread(Semaphore s,String n)
{
sem= s;
name= n;
new Thread(this).start();
}
public void run()
{

System.out.println("Starting" + name);
try
{
System.out.println(name + " is waiting for a permit. ");
sem.acquire();
System.out.println(name + " gets a permit.");
for(int i=0;i<5;i++)
{
Shared.count--;
System.out.println(name +":"+ Shared.count);
Thread.sleep(10);}
}
catch(InterruptedException exc)
{

System.out.println(exc);
}
System.out.println(name + "releases the permit.");
sem.release()
}

OUTPUT
Starting A
Starting B
B is waiting for a permit.
B gets a permit.
A is waiting for a permit.
B: 0
A: 0
A: 1
B: 0
B: 0
A: 0
B: 0
A: 0
B: 1
A: 0
A releases the permit.
B releases the permit.

RESULT
Thus the java program involving concurrency using Semaphore is executed and the output is
verified.

Ex. No :
6
DATE :

SYNCHRONIZATION OF QUEUE

AIM
To write a java program to implement the synchronization of queue.

ALGORITHM
STEP 1: Include all header files
STEP 2: Using main function create object to the class
STEP 3: Create a new Thread A and B
STEP 4: Using this keyword call the current thread
STEP 5: Execute the program and display the output.

PROGRAM
import java.util.concurrent.locks.*;
class LockDemo
{
public static void main(String args[])
{

ReentrantLock lock=new ReentrantLock();


new LockThread(lock,"A");
new LockThread(lock,"B");
}}

class Shared
{
static int count=0;
}
class LockThread implements Runnable
{
String name;
ReentrantLock lock;
LockThread(ReentrantLock lk,String n)
{
lock=lk;
name=n;
new Thread(this).start();
}
public void run()
{
System.out.println("Starting "+name);
try
{
System.out.println(name+"is waiting to lock count");
lock.lock();
System.out.println(name+"is locking count");

Shared.count++;
System.out.println(name+":"+Shared.count);
System.out.println(name+"is sleeping");
Thread.sleep(1000);
}
catch(InterruptedException exc)
{
System.out.println(exc);
}

finally

{
System.out.println(name+"is unlocking count");
lock.unlock();
}

OUTPUT
Starting A
A is waiting to lock count
Starting B
A is locking count
B is waiting to lock count
A: 1
A is sleeping
A is unlocking count
B is locking count
B: 2
B is sleeping
B is unlocking count

RESULT
Thus the java program to implement concurrent queue is executed and the output is verified.

Ex. No :
6
DATE :

IMPLEMENTATION OF QUICK SORT

AIM
To write a program to implement randomized quick sort algorithm.

ALGORITHM
RANDOMIZED-PARTITION(A,p,r)
iRANDOM(p,r)
exchange A[r]A[i]
return Partition(A,p,r)
RANDOMIZED QUICKSORT(A,p,r)
if p<r
then qRANDOMIZED-PARTITION(A,p,r)
RANDOMIZED-QUICKSORT(A,p,q-1)
RANDOMIZED-QUICKSORT(A,q+1,r)

PROGRAM
import java.util.Random;
import java.io.*;
public class QuickSort
{
public static void main(String[] args) throws IOException
{
int i,n;
System.out.println("\n\tImplementation of Quick Sort using Random Pivot\n\n");
System.out.print("Enter no of elements in the array : ");
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
int array[] = new int[n];
System.out.println("\nEnter the Numbers");
for(i=0;i<n;i++)
{ array[i] = Integer.parseInt(br.readLine()); }
System.out.println("\nValues Before the sort:");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println("\n");
quickSort(array,0,array.length-1);
System.out.print("\nValues after the sort:\n");
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
}
public static int partition(int arr[], int left, int right)

{
int i = left, j = right;
int tmp;
Random rnd = new Random();
int num=rnd.nextInt(right - left);
int pivot = arr[left+num];
System.out.println("Now pivot is :"+pivot);
while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}

} return i;

public static void quickSort(int arr[], int left, int right)


{
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)

quickSort(arr, index, right);


}
}

OUTPUT
Implementation of Quick Sort using Random Pivot
Enter no of elements in the array : 6
Enter the Numbers
44
67
23
49
78
19
Values Before the sort:
44 67 23 49 78 19
Now pivot is :67
Now pivot is :44
Now pivot is :23
Now pivot is :44
Now pivot is :78
Values after the sort:
19 23 44 49 67 78

RESULT
Thus the java program to implement randomized quick is executed and the output is verified.

Ex. No :
6
DATE :

SYNCHRONIZATION OF STACK

AIM
To write a java program to implement the synchronization of stack.

ALGORITHM
STEP 1: Include all header files
STEP 2: Using main function create object to the class
STEP 3: Using pop and push create a stack
STEP 4: Using the various operations display the stack variables
STEP 5: Execute the program and display the output.

PROGRAM
import java.util.*;
class StackDemo
{
static void showpush(Stack st, int a)
{
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st)
{
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[])
{
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try
{
showpop(st);
}
catch (EmptyStackException e)
{
System.out.println("empty stack");

}
}}
OUTPUT
stack: []
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: []
pop -> empty stack

RESULT
Thus the java program to implement concurrent stack is executed and the output is verified.

You might also like