Daafile
Daafile
Daafile
OF ALGORITHMS
Practical File
COCSC06
import java.util.Arrays;
import java.util.Random;
public class Practice {
public static void main(String[] args) {
int[] nValues = {10, 50, 100, 20};
for (int n : nValues) {
int[] array = generateRandomArray(n);
long startTime = System.currentTimeMillis();
quickSort(array, 0, array.length - 1);
long endTime = System.currentTimeMillis();
System.out.println("Sorted array for n=" + n + ": " + Arrays.toString(array));
System.out.println("Time taken to sort for n=" + n + ": " + (endTime - startTime) + "
milliseconds\n");
}
}
private static void quickSort(int[] array, int low, int high) {
if (low < high) {
int partitionIndex = partition(array, low, high);
quickSort(array, low, partitionIndex - 1);
quickSort(array, partitionIndex + 1, high);
}
}
private static int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = low - 1;
return i + 1;
}
private static int[] generateRandomArray(int size) {
int[] array = new int[size];
Random random = new Random();
Output:
2. Implement a Merge Sort algorithm to sort a given set of elements and determine the
time required to sort the elements. Repeat the experiment for different values of n, the
number of elements in the list to be sorted. The elements can be read from a file or can
be generated using the random number generator
import java.util.Arrays;
import java.util.Random;
public class MergeSortExample {
public static void main(String[] args) {
// Change the values in the array to experiment with different sizes
int[] arraySizes = {100, 500, 1000, 5000, 10000};
for (int n : arraySizes) {
int[] arr = generateRandomArray(n);
long startTime = System.nanoTime();
mergeSort(arr);
long endTime = System.nanoTime();
long duration = (endTime - startTime) / 1000000; // Convert to milliseconds
System.out.println("Array size: " + n + "\tTime taken: " + duration + " milliseconds");
}
}
private 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); // You can adjust the range of random numbers as needed
}
return arr;
}
private static void mergeSort(int[] arr) {
if (arr.length > 1) {
int mid = arr.length / 2;
int[] left = Arrays.copyOfRange(arr, 0, mid);
int[] right = Arrays.copyOfRange(arr, mid, arr.length);
mergeSort(left);
mergeSort(right);
public RedBlackTree() {
super();
root = null;
}
// Node class representing the elements of the tree
class Node {
int data;
Node left;
Node right;
char colour; // 'R' for red, 'B' for black
Node parent;
Node(int data) {
super();
this.data = data;
this.left = null;
this.right = null;
this.colour = 'R'; // Initializing the node color to red
this.parent = null;
}
}
if (y != null) {
y.parent = node;
}
return x;
}
if (y != null) {
y.parent = node;
}
return x;
}
if (root != this.root) {
if (root.colour == 'R' && root.left.colour == 'R') {
f = true;
}
}
} else {
root.right = insertHelp(root.right, data);
root.right.parent = root;
if (root != this.root) {
if (root.colour == 'R' && root.right.colour == 'R') {
f = true;
}
}
}
return root;
}
t.inorderTraversal();
System.out.println();
}
t.printTree();
}
}
OUTPUT :
4. Implement Radix Sort and Bucket Sort algorithms and compare their performance on a
set of randomly generated integers.
public class Practice {
public static void radixSort(int[] array) {
int max = Arrays.stream(array).max().getAsInt();
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(array, exp);
}
}
private static void countingSort(int[] array, int exp) {
int n = array.length;
int[] output = new int[n];
int[] count = new int[10];
Arrays.fill(count, 0);
for (int i = 0; i < n; i++) {
count[(array[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
output[count[(array[i] / exp) % 10] - 1] = array[i];
count[(array[i] / exp) % 10]--;
}
System.arraycopy(output, 0, array, 0, n);
}
public static void bucketSort(int[] array) {
int max = Arrays.stream(array).max().getAsInt();
int min = Arrays.stream(array).min().getAsInt();
int range = max - min + 1;
int bucketSize = 5;
int bucketCount = (range / bucketSize) + 1;
List<List<Integer>> buckets = new ArrayList<>(bucketCount);
for (int i = 0; i < bucketCount; i++) {
buckets.add(new LinkedList<>());
}
for (int value : array) {
int bucketIndex = (value - min) / bucketSize;
buckets.get(bucketIndex).add(value);
}
int currentIndex = 0;
for (List<Integer> bucket : buckets) {
insertionSort(bucket);
for (int value : bucket) {
array[currentIndex++] = value;
}
}
}
private static void insertionSort(List<Integer> bucket) {
for (int i = 1; i < bucket.size(); i++) {
int current = bucket.get(i);
int j = i - 1;
while (j >= 0 && bucket.get(j) > current) {
bucket.set(j + 1, bucket.get(j));
j--;
}
bucket.set(j + 1, current);
}
}
public static void main(String[] args) {
int[] array = generateRandomArray(100000, 1, 100000);
long startTimeRadix = System.currentTimeMillis();
radixSort(array.clone());
long endTimeRadix = System.currentTimeMillis();
System.out.println("Radix Sort Time: " + (endTimeRadix - startTimeRadix) + " ms");
long startTimeBucket = System.currentTimeMillis();
bucketSort(array.clone());
long endTimeBucket = System.currentTimeMillis();
System.out.println("Bucket Sort Time: " + (endTimeBucket - startTimeBucket) + " ms");
}
private static int[] generateRandomArray(int size, int minValue, int maxValue) {
int[] array = new int[size];
Random random = new Random();
for (int i = 0; i < size; i++) {
array[i] = random.nextInt(maxValue - minValue + 1) + minValue;
}
return array;
}
}
Output:
class Item {
int weight;
int value;
6.
A) Obtain the Topological ordering of vertices in a given digraph.
public class topologiclasort {
static class Edge{
int src;
int dest;
public Edge(int src,int dest){
this.src=src;
this.dest=dest;
}
}
public static void createGraph(ArrayList<Edge> graph[]){
for(int i=0;i<graph.length;i++){
graph[i]=new ArrayList<>();
}
graph[0].add(new Edge(0,3));
graph[2].add(new Edge(2,3));
graph[3].add(new Edge(3,1));
graph[4].add(new Edge(4,1));
graph[4].add(new Edge(4,0));
graph[5].add(new Edge(5,0));
graph[5].add(new Edge(5,2));
}
public static void topSort(ArrayList<Edge> graph[]){
boolean vis[]=new boolean[graph.length];
Stack<Integer> st=new Stack<>();
for(int i=0;i<graph.length;i++){
if(!vis[i]) topSortUtil(graph,i,vis,st);
}
while(!st.isEmpty()) System.out.print(st.pop()+" ");
}
public static void topSortUtil(ArrayList<Edge> graph[],int curr,boolean vis[],Stack<Integer>
st){
vis[curr]=true;
for(int i=0;i<graph[curr].size();i++){
Edge e=graph[curr].get(i);
if(!vis[e.dest]) topSortUtil(graph,e.dest,vis,st);
}
st.push(curr);
}
Output:
8. From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijikstra’s algorithm
public static void dijkstra(ArrayList<Edge> graph[],int src){
int dist[]=new int[graph.length];
for(int i=0;i<graph.length;i++) {
if(i!=src){
dist[i]=Integer.MAX_VALUE;
}
}
boolean vis[]=new boolean[graph.length];
PriorityQueue<Pair> pq=new PriorityQueue<>();
pq.add(new Pair(src,0));
while(!pq.isEmpty()){
Pair curr=pq.remove();
if(!vis[curr.n]){
vis[curr.n]=true;
for(int i=0;i<graph[curr.n].size();i++){
Edge e=graph[curr.n].get(i);
int u=e.src;
int v=e.dest;
int wt=e.wt;
if(dist[u]+wt<dist[v]){
dist[v]=dist[u]+wt;
pq.add(new Pair(v,dist[v]));
}
}
}
}
for(int i=0;i<dist.length;i++){
System.out.print(dist[i]+" ");
}
}
Output:
9. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s algorithm.
Output:
10.
(A) Print all the nodes reachable from a given starting node in a digraph using BFS method.
public class BFSGraph {
private int vertices;
private ArrayList<Integer>[] adjList;
public BFSGraph(int vertices) {
this.vertices = vertices;
adjList = new ArrayList[vertices];
for (int i = 0; i < vertices; i++) {
adjList[i] = new ArrayList<>();
}
}
public void addEdge(int source, int destination) {
adjList[source].add(destination);
}
public void BFS(int startNode) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[startNode] = true;
queue.add(startNode);
while (!queue.isEmpty()) {
int currentNode = queue.poll();
System.out.print(currentNode + " ");
for (int neighbor : adjList[currentNode]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
}
public static void main(String[] args) {
BFSGraph graph = new BFSGraph(7);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 5);
graph.addEdge(2, 6);
int startNode = 0;
System.out.println("BFS starting from node " + startNode + ":");
graph.BFS(startNode);
}
}
Output:
(B) Check whether a given graph is connected or not using DFS method.
Output:
Q 11 Find a subset of a given set S of n integers whose sum is equal to a given positive
integer d . For example , if S = {1,2,5,6,8} and d= 9 there are two solutions {1,2,6} and {1,8}
. A suitable message is to be dislayed if the given problem instance doesn’t have a
solution .
import java.util.*;
public static void findSubsets(int[] set, int i, int sum, List<Integer> subset, List<List<Integer>>
subsets) {
if (sum == 0) {
subsets.add(new ArrayList<>(subset));
return;
}
subset.add(set[i]);
int s = sum - set[i];
findSubsets(set,i+1, s, subset, subsets);
subset.remove(subset.size() - 1);
}
if (subsets.size() == 0) {
System.out.println("No subset found with the given sum");
} else {
System.out.println("Subsets with sum " + d + ":");
for (List<Integer> sub : subsets) {
System.out.println(sub);
}
}
}
}
Output :
Q 12 Implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then solve the same problem instance using any approximation algorithm
and determine the error in the approximation.
import java.util.Arrays;
public class abc {
static int[][] adjacencyMatrix = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
static int n = adjacencyMatrix.length;
static int[][] memo;
public static void main(String[] args) {
memo = new int[n][1 << n];
for (int[] row : memo) {
Arrays.fill(row, -1);
}
int[] approxTour = nearestNeighbor();
System.out.println("Approximation Tour Length: " + calculateTourLength(approxTour));
int optimalTourLength = tsp(0, 1);
System.out.println("Optimal Tour Length: " + optimalTourLength);
}
public static int tsp(int currentCity, int visited) {
if (visited == (1 << n) - 1) {
return adjacencyMatrix[currentCity][0];
}
if (memo[currentCity][visited] != -1) {
return memo[currentCity][visited];
}
int minDistance = Integer.MAX_VALUE;
for (int nextCity = 0; nextCity < n; nextCity++) {
if ((visited & (1 << nextCity)) == 0) {
int newVisited = visited | (1 << nextCity);
int distance = adjacencyMatrix[currentCity][nextCity] + tsp(nextCity, newVisited);
minDistance = Math.min(minDistance, distance);
}
}
memo[currentCity][visited] = minDistance;
return minDistance;
}
Output:
Q 13 Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm .
import java.util.*;
public class ques13 {
graph[1].add(new Edge(1,0,10));
graph[1].add(new Edge(1,3,40));
graph[2].add(new Edge(2,0,15));
graph[2].add(new Edge(2,3,50));
graph[3].add(new Edge(3,0,30));
graph[3].add(new Edge(3,1,40));
graph[3].add(new Edge(3,2,50));
}
pq.add(new Pair(0,0));
int finalCost =0;
while(!pq.isEmpty()){
Pair curr = pq.remove();
if(!vis[curr.v]){
vis[curr.v] = true;
finalCost += curr.cost;
for(int i=0 ; i<graph[curr.v].size() ; i++){
Edge e = graph[curr.v].get(i);
pq.add(new Pair(e.dest,e.wt));
}
}
}
@SuppressWarnings("unchecked")
ArrayList<Edge> graph[] = new ArrayList[7];
OUTPUT :
printAns(dist);
}
public static void main(String args[]){
int[][] graph = {{0,2,4,9999},
{2,0,1,3},
{4,1,0,5},
{9999,3,5,0}};
floyd(graph);
}
}
OUTPUT :