You are on page 1of 29

Q1= Write a javaprogram to implement the Stack using arrays.

Write Push(),Pop(), and Display()methods


to

demonstrate its working.

Ans=

public class StackUsingArray {

private int maxSize;

private int top;

private int[] stackArray;

public StackUsingArray(int size) {

maxSize = size;

stackArray = new int[maxSize];

top = -1; // Initialize the top of the stack to -1 (empty stack).

public boolean isFull() {

return top == maxSize - 1;

public boolean isEmpty() {

return top == -1;

public void push(int value) {

if (isFull()) {

System.out.println("Stack is full. Cannot push " + value);


} else {

stackArray[++top] = value;

System.out.println(value + " pushed onto the stack.");

public int pop() {

if (isEmpty()) {

System.out.println("Stack is empty. Cannot pop.");

return -1; // Return -1 to indicate an error.

} else {

int poppedValue = stackArray[top--];

System.out.println("Popped: " + poppedValue);

return poppedValue;

public void display() {

if (isEmpty()) {

System.out.println("Stack is empty.");

} else {

System.out.print("Stack elements: ");

for (int i = 0; i <= top; i++) {

System.out.print(stackArray[i] + " ");

}
System.out.println();

public static void main(String[] args) {

StackUsingArray stack = new StackUsingArray(5);

stack.push(1);

stack.push(2);

stack.push(3);

stack.display();

stack.pop();

stack.display();

stack.push(4);

stack.push(5);

stack.push(6); // Trying to push onto a full stack.

stack.display();

(2) Write a java program to sort a list of elements using the quick sort algorithm. The elements can be
read from a file
ans=import java.io.*;

import java.util.ArrayList;

import java.util.List;

public class QuickSortFile {

public static void main(String[] args) {

String inputFileName = "input.txt"; // Replace with your input file name

String outputFileName = "output.txt"; // Replace with your output file name

try {

// Read elements from the input file

List<Integer> elements = readElementsFromFile(inputFileName);

// Perform Quick Sort

quickSort(elements, 0, elements.size() - 1);

// Write sorted elements to the output file

writeElementsToFile(outputFileName, elements);

} catch (IOException e) {

e.printStackTrace();

public static void quickSort(List<Integer> elements, int low, int high) {

if (low < high) {


int pivotIndex = partition(elements, low, high);

quickSort(elements, low, pivotIndex - 1);

quickSort(elements, pivotIndex + 1, high);

public static int partition(List<Integer> elements, int low, int high) {

int pivot = elements.get(high);

int i = low - 1;

for (int j = low; j < high; j++) {

if (elements.get(j) < pivot) {

i++;

int temp = elements.get(i);

elements.set(i, elements.get(j));

elements.set(j, temp);

int temp = elements.get(i + 1);

elements.set(i + 1, elements.get(high));

elements.set(high, temp);

return i + 1;

}
public static List<Integer> readElementsFromFile(String fileName) throws IOException {

List<Integer> elements = new ArrayList<>();

BufferedReader reader = new BufferedReader(new FileReader(fileName));

String line;

while ((line = reader.readLine()) != null) {

elements.add(Integer.parseInt(line));

reader.close();

return elements;

public static void writeElementsToFile(String fileName, List<Integer> elements) throws IOException {

BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));

for (Integer element : elements) {

writer.write(element + "\n");

writer.close();

(3)Write a java program to implement a Merge sort algorithm to a list of elements for different values of
n and

determine the time required to sort the elements

import java.util.Random;
public class MergeSortTiming {

public static void main(String[] args) {

int[] nValues = {1000, 5000, 10000, 50000, 100000};

for (int n : nValues) {

int[] arr = generateRandomArray(n);

long startTime = System.nanoTime(); // Record the start time

mergeSort(arr);

long endTime = System.nanoTime(); // Record the end time

long elapsedTime = endTime - startTime;

System.out.println("Time to sort " + n + " elements: " + elapsedTime + " nanoseconds");

public static int[] generateRandomArray(int n) {

int[] arr = new int[n];

Random random = new Random();

for (int i = 0; i < n; i++) {

arr[i] = random.nextInt(1000); // Generate random integers between 0 and 999

return arr;
}

public static void mergeSort(int[] arr) {

if (arr == null || arr.length <= 1) {

return; // No need to sort if the array is empty or has only one element

int n = arr.length;

int[] temp = new int[n];

mergeSort(arr, temp, 0, n - 1);

private static void mergeSort(int[] arr, int[] temp, int left, int right) {

if (left < right) {

int mid = (left + right) / 2;

mergeSort(arr, temp, left, mid);

mergeSort(arr, temp, mid + 1, right);

merge(arr, temp, left, mid, right);

private static void merge(int[] arr, int[] temp, int left, int mid, int right) {

for (int i = left; i <= right; i++) {

temp[i] = arr[i];

}
int i = left;

int j = mid + 1;

int k = left;

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

if (temp[i] <= temp[j]) {

arr[k] = temp[i];

i++;

} else {

arr[k] = temp[j];

j++;

k++;

while (i <= mid) {

arr[k] = temp[i];

i++;

k++;

}
(4)Find the minimum cost of spanning tree in java using Prim’s algorithms

Ans=import java.util.Arrays;

public class PrimMinimumSpanningTree {

private static final int V = 5; // Number of vertices

// Function to find the vertex with the minimum key value

private int minKey(int[] key, boolean[] mstSet) {

int min = Integer.MAX_VALUE, minIndex = -1;

for (int v = 0; v < V; v++) {

if (!mstSet[v] && key[v] < min) {

min = key[v];

minIndex = v;

return minIndex;

// Function to print the minimum spanning tree

private void printMST(int[] parent, int[][] graph) {

System.out.println("Edge \tWeight");

for (int i = 1; i < V; i++) {

System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);

}
// Function to find the minimum spanning tree using Prim's algorithm

private void primMST(int[][] graph) {

int[] parent = new int[V];

int[] key = new int[V];

boolean[] mstSet = new boolean[V];

Arrays.fill(key, Integer.MAX_VALUE);

key[0] = 0;

parent[0] = -1;

for (int count = 0; count < V - 1; count++) {

int u = minKey(key, mstSet);

mstSet[u] = true;

for (int v = 0; v < V; v++) {

if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {

parent[v] = u;

key[v] = graph[u][v];

printMST(parent, graph);

}
public static void main(String[] args) {

PrimMinimumSpanningTree prim = new PrimMinimumSpanningTree();

int[][] graph = new int[][] {

{0, 2, 0, 6, 0},

{2, 0, 3, 8, 5},

{0, 3, 0, 0, 7},

{6, 8, 0, 0, 9},

{0, 5, 7, 9, 0}

};

prim.primMST(graph);

(5)Find the minimum cost of spanning tree in java using Kruskal’s algorithm.

Ans=import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

class Edge {

int src, dest, weight;

Edge(int src, int dest, int weight) {

this.src = src;
this.dest = dest;

this.weight = weight;

class Graph {

int V, E; // Number of vertices and edges

List<Edge> edges;

Graph(int V, int E) {

this.V = V;

this.E = E;

edges = new ArrayList<>();

void addEdge(int src, int dest, int weight) {

Edge edge = new Edge(src, dest, weight);

edges.add(edge);

List<Edge> kruskalMST() {

List<Edge> result = new ArrayList<>();

Collections.sort(edges, Comparator.comparingInt(e -> e.weight));

int[] parent = new int[V];


for (int v = 0; v < V; v++) {

parent[v] = v;

int e = 0; // An index variable for result[]

int i = 0; // An index variable for sorted edges

while (e < V - 1) {

Edge nextEdge = edges.get(i++);

int x = find(parent, nextEdge.src);

int y = find(parent, nextEdge.dest);

if (x != y) {

result.add(nextEdge);

union(parent, x, y);

e++;

return result;

int find(int[] parent, int i) {

if (parent[i] != i) {

parent[i] = find(parent, parent[i]);

return parent[i];
}

void union(int[] parent, int x, int y) {

int xSet = find(parent, x);

int ySet = find(parent, y);

parent[xSet] = ySet;

public class KruskalMinimumSpanningTree {

public static void main(String[] args) {

int V = 5; // Number of vertices

int E = 7; // Number of edges

Graph graph = new Graph(V, E);

graph.addEdge(0, 1, 2);

graph.addEdge(0, 3, 6);

graph.addEdge(1, 2, 3);

graph.addEdge(1, 3, 8);

graph.addEdge(1, 4, 5);

graph.addEdge(2, 4, 7);

graph.addEdge(3, 4, 9);

List<Edge> mst = graph.kruskalMST();


System.out.println("Edges in the Minimum Spanning Tree:");

for (Edge edge : mst) {

System.out.println(edge.src + " - " + edge.dest + " : " + edge.weight);

(6) Implement 0/1 Knapsack problem using Dynamic Programming in java

Ans = public class KnapsackDP {

public static void main(String[] args) {

int[] weights = {2, 3, 4, 5};

int[] values = {3, 4, 5, 6};

int capacity = 5;

int n = weights.length;

int maxValue = knapsack(weights, values, capacity, n);

System.out.println("Maximum value: " + maxValue);

public static int knapsack(int[] weights, int[] values, int capacity, int n) {

int[][] dp = new int[n + 1][capacity + 1];

// Build the DP table

for (int i = 0; i <= n; i++) {


for (int w = 0; w <= capacity; w++) {

if (i == 0 || w == 0) {

dp[i][w] = 0;

} else if (weights[i - 1] <= w) {

dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);

} else {

dp[i][w] = dp[i - 1][w];

return dp[n][capacity];

(7) Write a java program to find the shortest paths between nodes in a graph using Dijkstra’s algorithm.

Ans=import java.util.Arrays;

public class DijkstraShortestPaths {

private static final int V = 5; // Number of vertices in the graph

public void dijkstra(int graph[][], int source) {

int[] dist = new int[V]; // Array to store the shortest distances from the source

boolean[] sptSet = new boolean[V]; // Array to track visited vertices


Arrays.fill(dist, Integer.MAX_VALUE);

dist[source] = 0;

for (int count = 0; count < V - 1; count++) {

int u = minDistance(dist, sptSet);

sptSet[u] = true;

for (int v = 0; v < V; v++) {

if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE

&& dist[u] + graph[u][v] < dist[v]) {

dist[v] = dist[u] + graph[u][v];

printSolution(dist);

private int minDistance(int[] dist, boolean[] sptSet) {

int min = Integer.MAX_VALUE, minIndex = -1;

for (int v = 0; v < V; v++) {

if (!sptSet[v] && dist[v] <= min) {

min = dist[v];

minIndex = v;
}

return minIndex;

private void printSolution(int[] dist) {

System.out.println("Vertex \t Distance from Source");

for (int i = 0; i < V; i++) {

System.out.println(i + " \t " + dist[i]);

public static void main(String[] args) {

int graph[][] = new int[][] {

{0, 4, 0, 0, 0},

{4, 0, 8, 0, 0},

{0, 8, 0, 7, 0},

{0, 0, 7, 0, 9},

{0, 0, 0, 9, 0}

};

DijkstraShortestPaths shortestPaths = new DijkstraShortestPaths();

shortestPaths.dijkstra(graph, 0);

}
(8) Write a java program

Print all the nodes reachable from a starting node in a digraph using BFS method.

Check whether a graph is connected or not using DFS method

Ans=import java.util.LinkedList;

import java.util.List;

import java.util.Queue;

import java.util.Stack;

class Graph {

private int V;

private List<Integer>[] adjList;

public Graph(int v) {

V = v;

adjList = new List[V];

for (int i = 0; i < V; i++) {

adjList[i] = new LinkedList<>();

public void addEdge(int u, int v) {

adjList[u].add(v);

}
public void BFS(int startNode) {

boolean[] visited = new boolean[V];

Queue<Integer> queue = new LinkedList<>();

visited[startNode] = true;

queue.add(startNode);

System.out.println("Nodes reachable from " + startNode + " using BFS:");

while (!queue.isEmpty()) {

int node = queue.poll();

System.out.print(node + " ");

for (int neighbor : adjList[node]) {

if (!visited[neighbor]) {

visited[neighbor] = true;

queue.add(neighbor);

System.out.println();

public void DFS(int startNode) {

boolean[] visited = new boolean[V];


Stack<Integer> stack = new Stack<>();

visited[startNode] = true;

stack.push(startNode);

while (!stack.isEmpty()) {

int node = stack.pop();

for (int neighbor : adjList[node]) {

if (!visited[neighbor]) {

visited[neighbor] = true;

stack.push(neighbor);

public boolean isConnected() {

boolean[] visited = new boolean[V];

int firstNode = -1;

for (int i = 0; i < V; i++) {

if (adjList[i].size() > 0) {

firstNode = i;

break;
}

if (firstNode == -1) {

return true; // An empty graph is considered connected

DFS(firstNode);

for (int i = 0; i < V; i++) {

if (!visited[i] && adjList[i].size() > 0) {

return false; // There is an unvisited node with neighbors, graph is not connected

return true;

public class GraphTraversal {

public static void main(String[] args) {

Graph graph = new Graph(7);

graph.addEdge(0, 1);

graph.addEdge(0, 2);

graph.addEdge(1, 3);
graph.addEdge(2, 4);

graph.addEdge(3, 5);

graph.addEdge(4, 5);

graph.addEdge(5, 6);

int startNode = 0;

graph.BFS(startNode);

if (graph.isConnected()) {

System.out.println("The graph is connected.");

} else {

System.out.println("The graph is not connected.");

(9) Write a java program to implement all pairs shortest paths problem using Floyd’s algorithm

Ans = public class FloydWarshall {

private static final int INF = 9999; // Infinity

public void floydWarshall(int[][] graph, int V) {

int[][] dist = new int[V][V];

// Initialize the dist array with the given graph


for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

dist[i][j] = graph[i][j];

// Find shortest paths through all vertices

for (int k = 0; k < V; k++) {

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

if (dist[i][k] + dist[k][j] < dist[i][j]) {

dist[i][j] = dist[i][k] + dist[k][j];

// Print the shortest paths

System.out.println("Shortest distances between all pairs of vertices:");

for (int i = 0; i < V; i++) {

for (int j = 0; j < V; j++) {

if (dist[i][j] == INF) {

System.out.print("INF\t");

} else {

System.out.print(dist[i][j] + "\t");
}

System.out.println();

public static void main(String[] args) {

int V = 4; // Number of vertices

int[][] graph = {

{0, 5, INF, 10},

{INF, 0, 3, INF},

{INF, INF, 0, 1},

{INF, INF, INF, 0}

};

FloydWarshall floydWarshall = new FloydWarshall();

floydWarshall.floydWarshall(graph, V);

(10) Write a java program to implement N Queen’s problem using Back Tracking.

Ans=public class NQueens {

public static void solveNQueens(int n) {

char[][] board = new char[n][n];

for (char[] row : board) {


Arrays.fill(row, '.');

List<List<String>> result = new ArrayList<>();

solveNQueensHelper(board, 0, result);

printSolutions(result);

private static void solveNQueensHelper(char[][] board, int row, List<List<String>> result) {

if (row == board.length) {

result.add(constructSolution(board));

return;

for (int col = 0; col < board.length; col++) {

if (isSafe(board, row, col)) {

board[row][col] = 'Q';

solveNQueensHelper(board, row + 1, result);

board[row][col] = '.';

private static boolean isSafe(char[][] board, int row, int col) {

int n = board.length;
// Check the column above

for (int i = 0; i < row; i++) {

if (board[i][col] == 'Q') {

return false;

// Check upper-left diagonal

for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {

if (board[i][j] == 'Q') {

return false;

// Check upper-right diagonal

for (int i = row, j = col; i >= 0 && j < n; i--, j++) {

if (board[i][j] == 'Q') {

return false;

return true;

private static List<String> constructSolution(char[][] board) {


List<String> solution = new ArrayList<>();

for (char[] row : board) {

solution.add(new String(row));

return solution;

private static void printSolutions(List<List<String>> solutions) {

for (List<String> solution : solutions) {

for (String row : solution) {

System.out.println(row);

System.out.println();

public static void main(String[] args) {

int n = 8; // Change n to the desired board size

solveNQueens(n);

You might also like