of 51
8/18/2019 ADS Record Final.pdf
1/51
8/18/2019 ADS Record Final.pdf
2/51
PROGRAM
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFS
{
private Queue queue;
public BFS()
{
queue = new LinkedList();
}
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
8/18/2019 ADS Record Final.pdf
3/51
{
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
8/18/2019 ADS Record Final.pdf
4/51
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
0 1 1 0
0 0 0 1
0 0 0 1
0 0 0 0
Enter the source for the graph
1
The BFS traversal of the graph is
1 2 3 4
RESULT
Thus the java program to implement bipartite is executed and the output is verified.
8/18/2019 ADS Record Final.pdf
5/51
AIM
To write a java program to implement graph searching algorithm using Depth First Search.
ALGORITHM
begin foundHandled =path
foundNotHandled ={}
time= 0 % Used fortime stamping.
loop
exit when foundNotHandled =path
pop off the stack foundNotHandled
if u has an (i+1)st edge
pushonto foundNotHandled
if v has not previously been found then
π(v) =u ; is a tree edge
push onto foundNotHandled
s(v) =time; time=time+1
else if v has been found but not completely handled then is a back edge
else (v has been completely handled) is a forward or cross edge
end if
else move u to foundHandled f(v) =time; time=time+1end if
end loop
return foundHandled end
DEPTH FIRST SEARCH
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
6/51
PROGRAM
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class DFS{
private Stack stack;
public DFS()
{
stack = new Stack();
}
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
8/18/2019 ADS Record Final.pdf
7/51
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
8/18/2019 ADS Record Final.pdf
8/51
System.out.println("Wrong Input format");
}
scanner.close();
}
OUTPUT
Enter the number of nodes in the graph
4
Enter the adjacency matrix
0 1 1 0
0 0 0 1
0 0 0 1
0 0 0 0
Enter the source for the graph
1
The DFS Traversal for the graph is given by
1 2 4 3
RESULT
Thus the java program for implementing Depth first search using graph search algorithm is
executed and output is verified.
8/18/2019 ADS Record Final.pdf
9/51
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)
TRAVELLING SALESMAN PROBLEM
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
10/51
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? ");
8/18/2019 ADS Record Final.pdf
11/51
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");
}
8/18/2019 ADS Record Final.pdf
12/51
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)
8/18/2019 ADS Record Final.pdf
13/51
{
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);
}
}}
8/18/2019 ADS Record Final.pdf
14/51
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 outputverified.
8/18/2019 ADS Record Final.pdf
15/51
AIM
To write a program to find the shortest path between the vertices using Dijikstra's algorithm.
ALGORITHM
begin
d(s) = 0, π(s) = null
for other v, d(v) =∞and π(v) =nil
handled =∅
notHandled =priority queue containing all nodes. Priorities given by d(v).
loop
:
exit when notHandled =∅
let u be a node from notHandled with smallest d(u)
for eachv connected to u
foundPathLength =d(u)+w
if d(v) > foundPathLength then
d(v) = foundPathLength ; π(v) =u
end if
end for
move u from notHandled to handled
end loop
return
end
DYNAMIC PROGRAMMING DESIGN TECHNIQUE
-DIJIKSTRA’S ALGORITHM
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
16/51
PROGRAM
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable{
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;
8/18/2019 ADS Record Final.pdf
17/51
public Edge(Vertex argTarget, double argWeight)
{
target = argTarget;
weight = argWeight;
}
}
public class Dijkstra
{
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue vertexQueue = new PriorityQueue();
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);
8/18/2019 ADS Record Final.pdf
18/51
}
}
}
}
public static List getShortestPathTo(Vertex target)
{
List path = new ArrayList();
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)};
8/18/2019 ADS Record Final.pdf
19/51
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 path = getShortestPathTo(v);
System.out.println("Path: " + path);
}
}
}
8/18/2019 ADS Record Final.pdf
20/51
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.
8/18/2019 ADS Record Final.pdf
21/51
AIM
To write a program to implement knapsack problem
ALGORITHM
knapsack(i,j)
begin
if V[i,j]
8/18/2019 ADS Record Final.pdf
22/51
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
8/18/2019 ADS Record Final.pdf
23/51
for(i=0;i
8/18/2019 ADS Record Final.pdf
24/51
8/18/2019 ADS Record Final.pdf
25/51
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
else
loop k = 1...n
C'_ = C ∪< r +1, k>
=Queens_C_, n,r +1>
end for
kmax =a k that maximizes optCostk,
optSol = optSolkmax
optCost = optCostkmax
return
end if
end
BACKTRACKING ALGORITHM USING N-QUEENS
PROBLEM
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
26/51
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();
}
8/18/2019 ADS Record Final.pdf
27/51
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);
}
}
8/18/2019 ADS Record Final.pdf
28/51
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.
8/18/2019 ADS Record Final.pdf
29/51
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();
PRODUCER CONSUMER PROBLEM
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
30/51
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()
8/18/2019 ADS Record Final.pdf
31/51
{
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)
8/18/2019 ADS Record Final.pdf
32/51
{
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
8/18/2019 ADS Record Final.pdf
33/51
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);
}
}
8/18/2019 ADS Record Final.pdf
34/51
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: 9Queue is empty Now
RESULT
Thus the java program to implement Producer Consumer problem is executed and the output
verified.
8/18/2019 ADS Record Final.pdf
35/51
8/18/2019 ADS Record Final.pdf
36/51
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++;
8/18/2019 ADS Record Final.pdf
37/51
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.
8/18/2019 ADS Record Final.pdf
38/51
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.
IMPLEMENTATION OF SEMAPHORES
INVOLVING CONCURRENCY
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
39/51
8/18/2019 ADS Record Final.pdf
40/51
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
8/18/2019 ADS Record Final.pdf
41/51
8/18/2019 ADS Record Final.pdf
42/51
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.
SYNCHRONIZATION OF QUEUE
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
43/51
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");
8/18/2019 ADS Record Final.pdf
44/51
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.
8/18/2019 ADS Record Final.pdf
45/51
8/18/2019 ADS Record Final.pdf
46/51
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
8/18/2019 ADS Record Final.pdf
47/51
{
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 pivot)
j--;
if (i
8/18/2019 ADS Record Final.pdf
48/51
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.
8/18/2019 ADS Record Final.pdf
49/51
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.
SYNCHRONIZATION OF STACK
Ex. No :
DATE :
8/18/2019 ADS Record Final.pdf
50/51
8/18/2019 ADS Record Final.pdf
51/51
}
}}
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