You are on page 1of 18

Write a program to sort a list of N elements using Selection sort technique

import java.util.*;
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n - 1; i++)
{
int min_idx = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[min_idx])
min_idx = j;
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements");
n=sc.nextInt();
System.out.println("Enter the numbers to be sorted");
int [] arr= new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
Write a Program to perform Travelling salesman problem

import java.util.*;
import java.io.*;
import java.util.Scanner;
class TSPExample
{
static int findHamiltonianCycle(int[][] distance, boolean[] visitCity, int currPos, int cities, int
count, int cost, int hamiltonianCycle)
{
if (count == cities && distance[currPos][0] > 0)
{
hamiltonianCycle = Math.min(hamiltonianCycle, cost + distance[currPos][0]);
return hamiltonianCycle;
}
for (int i = 0; i < cities; i++)
{
if (visitCity[i] == false && distance[currPos][i] > 0)
{
visitCity[i] = true;
hamiltonianCycle = findHamiltonianCycle(distance, visitCity, i, cities, count
+ 1, cost + distance[currPos][i], hamiltonianCycle);
}
}
return hamiltonianCycle;
}
public static void main(String[] args)
{
int cities;
Scanner sc = new Scanner(System.in);
System.out.println("Enter total number of cities ");
cities = sc.nextInt();
int distance[][] = new int[cities][cities];
for( int i = 0; i < cities; i++)
{
for( int j = 0; j < cities; j++)
{
System.out.println("Distance from city"+ (i+1) +" to city"+ (j+1) +": ");
distance[i][j] = sc.nextInt();
}
}
boolean[] visitCity = new boolean[cities];
visitCity[0] = true;
int hamiltonianCycle = Integer.MAX_VALUE;
hamiltonianCycle = findHamiltonianCycle(distance, visitCity, 0, cities, 1, 0,
hamiltonianCycle);
System.out.println(hamiltonianCycle);
}
}
Write a program to perform Knapsack problem using Greedy solution.

import java.util.Scanner;
class Knapsack
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int object,m;
System.out.println("Enter the Total Objects");
object=sc.nextInt();
int weight[]=new int[object];
int profit[]=new int[object];
for(int i=0;i<object;i++)
{
System.out.println("Enter the Profit for "+"Object "+(i+1));
profit[i]=sc.nextInt();
System.out.println("Enter the weight for "+"Object "+(i+1));
weight[i]=sc.nextInt();
}
System.out.println("Enter the Knapsack capacity");
m=sc.nextInt();
double p_w[]=new double[object];
for(int i=0;i<object;i++)
{
p_w[i]=(double)profit[i]/(double)weight[i];
}
System.out.println("");
System.out.println("-------------------");
System.out.println("-----Data-Set------");
System.out.print("-------------------");
System.out.println("");
System.out.print("Objects");
for(int i=1;i<=object;i++)
{
System.out.print(i+" ");
}
System.out.println();
System.out.print("Profit ");
for(int i=0;i<object;i++)
{
System.out.print(profit[i]+" ");
}
System.out.println();
System.out.print("Weight ");
for(int i=0;i<object;i++)
{
System.out.print(weight[i]+" ");
}
System.out.println();
System.out.print("P/W ");
for(int i=0;i<object;i++)
{
System.out.print(p_w[i]+" ");
}
for(int i=0;i<object-1;i++)
{
for(int j=i+1;j<object;j++)
{
if(p_w[i]<p_w[j])
{
double temp=p_w[j];
p_w[j]=p_w[i];
p_w[i]=temp;
int temp1=profit[j];
profit[j]=profit[i];
profit[i]=temp1;
int temp2=weight[j];
weight[j]=weight[i];
weight[i]=temp2;
}
}
}
System.out.println("");
System.out.println("-------------------");
System.out.println("--After Arranging--");
System.out.print("-------------------");
System.out.println("");
System.out.print("Objects");
for(int i=1;i<=object;i++)
{
System.out.print(i+" ");
}
System.out.println();
System.out.print("Profit ");
for(int i=0;i<object;i++)
{
System.out.print(profit[i]+" ");
}
System.out.println();
System.out.print("Weight ");
for(int i=0;i<object;i++)
{
System.out.print(weight[i]+" ");
}
System.out.println();
System.out.print("P/W ");
for(int i=0;i<object;i++)
{
System.out.print(p_w[i]+" ");
}
int k=0;
double sum=0;
System.out.println();
while(m>0)
{
if(weight[k]<m)
{
sum+=1*profit[k];
m=m-weight[k];
}
else
{
double x4=m*profit[k];
double x5=weight[k];
double x6=x4/x5;
sum=sum+x6;
m=0;
}
k++;
}
System.out.println("Final Profit is="+sum);
}
}

Java program to print BFS traversal from a given source vertex.

import java.io.*;
import java.util.*;
class Graph
{
private int V;
private LinkedList<Integer> adj[];
Graph(int v)
{
V = v;
adj = new LinkedList[v]; for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v,int w)
{
adj[v].add(w);
}
void BFS(int s)
{
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
s = queue.poll();
System.out.print(s+" ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next(); if (!visited[n])
{
visited[n] = true; queue.add(n);
}
}
}
}
public static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Breadth First Traversal "+"(starting from vertex 2)");
g.BFS(2);
}
}

Java program to print DFS traversal from a given graph


import java.io.*;
import java.util.*;
class DFSGraph
{
private int V;
private LinkedList<Integer> adj[];
DFSGraph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v, int w)
{
adj[v].add(w);
}
void DFSUtil(int v,boolean visited[])
{
visited[v] = true;
System.out.print(v+" ");
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n,visited);
}
}
void DFS()
{
boolean visited[] = new boolean[V];
for (int i=0; i<V; ++i)
if (visited[i] == false)
DFSUtil(i, visited);
}
public static void main(String args[])
{
DFSGraph g = new
DFSGraph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Depth First Traversal");
g.DFS();
}
}

Program to find minimum and maximum value in an array using divide and conquer

class Pair
{
public int max, min;
public Pair(int max, int min)
{
this.max = max;
this.min = min;
}
}
class MinMaxDAC
{
public static void findMinAndMax(int[] nums, int left, int right, Pair p)
{
if(left == right)
{
if(p.max < nums[left])
{
p.max = nums[left];
}
if(p.min > nums[right])
{
p.min = nums[right];
}
return;
}
if(right - left == 1)
{
if(nums[left] < nums[right])
{
if(p.min > nums[left])
{
p.min = nums[left];
}
if(p.max < nums[right])
{
p.max = nums[right];
}
}
else
{
if(p.min > nums[right])
{
p.min = nums[right];
}
if(p.max < nums[left])
{
p.max = nums[left];
}
}
return;
}
int mid = (left + right) / 2;
findMinAndMax(nums, left, mid, p);
findMinAndMax(nums, mid + 1, right, p);
}
public static void main(String[] args)
{
int[] nums = { 7, 2, 9, 3, 1, 6, 7, 8, 4 };
Pair p = new Pair(Integer.MIN_VALUE, Integer.MAX_VALUE);
findMinAndMax(nums, 0, nums.length - 1, p);
System.out.println("The minimum array element is " + p.min);
System.out.println("The maximum array element is " + p.max);
}
}

Write a program to implement Merge sort algorithm for sorting a list of integers in
ascending order.

import java.util.*;
import java.io.*;
public class MergeSort
{
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int[n1];
int R[] = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
int i = 0, j = 0;
int k = l;
while(i < n1 && j < n2)
{
if(L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while(i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while(j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r)
{
if(l < r)
{
int m = (l + r) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter the total number of elements");
n=sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter the array elements");
for (int i=0;i<n;i++)
arr[i]=sc.nextInt();
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.length - 1);
System.out.println("\nSorted array");
printArray(arr);
}
}

Sort a given set of n integer elements using Merge sort method and compute its time
complexity. Run the program for varied vaues of n> 5000 and record the time taken to
sort.

import java.util.Random;
import java.util.Scanner;
public class mergesort
{
static int max=10000;
void merge( int[] array,int low, int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
int[]resarray;
resarray=new int[max];
while(i<=mid&&j<=high)
{
if(array[i]<=array[j])
{
resarray[k]=array[i];
i++;
k++;
}
else
{
resarray[k]=array[j];
j++;
k++;
}
}
while(i<=mid)
resarray[k++]=array[i++];
while(j<=high)
resarray[k++]=array[j++];
for(int m=low;m<=high;m++)
array[m]=resarray[m];
}
void sort( int[] array,int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
sort(array,low,mid);
sort(array,mid+1,high);
merge(array,low,mid,high);
}
}
public static void main(String[] args)
{
int[] array;
int i;
System.out.println("Enter the array size");
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
array= new int[max];
Random generator=new Random();
for( i=0;i<n;i++)
array[i]=generator.nextInt(100);
System.out.println("Array before sorting");
for( i=0;i<n;i++)
System.out.println(array[i]+" ");
long startTime=System.nanoTime();
mergesort m=new mergesort();
m.sort(array,0,n-1);
long stopTime=System.nanoTime();
long elapseTime=(stopTime-startTime);
System.out.println("Time taken to sort array is:"+elapseTime+"nano seconds");
System.out.println("Sorted array is");
for(i=0;i<n;i++)
System.out.println(array[i]);
}
}

Sort a given set of n integer elements using Quick sort method and compute its time
complexity. Run the program for varied vaues of n> 5000 and record the time taken to
sort.

import java.util.Random;
import java.util.Scanner;
public class Quick_sort
{
static int max = 10000;
int partition(int[] a, int low, int high)
{
int p, i, j, temp;
p = a[low];
i = low + 1;
j = high;
while (low < high) {
while (a[i] <= p && i < high)
i++;
while (a[j] > p)
j--;
if (i < j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
else
{
temp = a[low];
a[low] = a[j];
a[j] = temp;
return j;
}
}
return j;
}
void sort(int[] a, int low, int high)
{
if (low < high)
{
int s = partition(a, low, high);
sort(a, low, s - 1);
sort(a, s + 1, high);
}
}

public static void main(String[] args)


{
int[] a;
int i, n;
System.out.println("Enter the array size");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
a = new int[max];
Random generator = new Random();
for (i = 0; i < n; i++)
a[i] = generator.nextInt(100);
System.out.println("Array before sorting");
for (i = 0; i < n; i++)
System.out.println(a[i] + " ");
long startTime = System.nanoTime();
Quick_sort m = new Quick_sort();
m.sort(a, 0, n - 1);
long stopTime = System.nanoTime();
long elapseTime = (stopTime - startTime);
System.out.println("Time taken to sort array is:" + elapseTime + "nano seconds");
System.out.println("Sorted array is");

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


System.out.println(a[i]);
}
}

Program that accepts the vertices and edges for a graph and stores it as an adjacency
matrix.

import java.util.Scanner;
public class Graph_Adjacency_Matrix
{
private final int vertices;
private int[][] adjacency_matrix;

public Graph_Adjacency_Matrix(int v)
{
vertices = v;
adjacency_matrix = new int[vertices + 1][vertices + 1];
}

public void makeEdge(int to, int from, int edge)


{
try
{
adjacency_matrix[to][from] = edge;
}
catch (ArrayIndexOutOfBoundsException index)
{
System.out.println("The vertices does not exists");
}
}
public int getEdge(int to, int from)
{
try
{
return adjacency_matrix[to][from];
}
catch (ArrayIndexOutOfBoundsException index)
{
System.out.println("The vertices does not exists");
}
return -1;
}
public static void main(String args[])
{
int v, e, count = 1, to = 0, from = 0;
Scanner sc = new Scanner(System.in);
Graph_Adjacency_Matrix graph;
try
{
System.out.println("Enter the number of vertices: ");
v = sc.nextInt();
System.out.println("Enter the number of edges: ");
e = sc.nextInt();
graph = new Graph_Adjacency_Matrix(v);
System.out.println("Enter the edges: <to> <from>");
while (count <= e)
{
to = sc.nextInt();
from = sc.nextInt();

graph.makeEdge(to, from, 1);


count++;
}
System.out.println("The adjacency matrix for the given graph is: ");
System.out.print(" ");
for (int i = 1; i <= v; i++)
System.out.print(i + " ");
System.out.println();
for (int i = 1; i <= v; i++)
{
System.out.print(i + " ");
for (int j = 1; j <= v; j++)
System.out.print(graph.getEdge(i, j) + " ");
System.out.println();
}
}
catch (Exception E)
{
System.out.println("Somthing went wrong");
}
sc.close();
}
}

Implement function to print In-Degree, Out-Degree and to display that adjacency


matrix.

import java.util.Scanner;
public class DirectedGraph
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of vertices: ");
int vertices = scanner.nextInt();
int[][] adjacencyMatrix = new int[vertices][vertices];
System.out.println("Enter the adjacency matrix (1 for edge, 0 for no edge):");
for (int i = 0; i < vertices; i++)
{
for (int j = 0; j < vertices; j++)
{
adjacencyMatrix[i][j] = scanner.nextInt();
}
}
printInDegree(adjacencyMatrix, vertices);
printOutDegree(adjacencyMatrix, vertices);
displayAdjacencyMatrix(adjacencyMatrix, vertices);
scanner.close();
}
private static void printInDegree(int[][] adjacencyMatrix, int vertices)
{
System.out.println("\nIn-Degree of vertices:");
for (int i = 0; i < vertices; i++)
{
int inDegree = 0;
for (int j = 0; j < vertices; j++)
{
inDegree += adjacencyMatrix[j][i];
}
System.out.println("Vertex " + i + ": " + inDegree);
}
}
private static void printOutDegree(int[][] adjacencyMatrix, int vertices)
{
System.out.println("\nOut-Degree of vertices:");
for (int i = 0; i < vertices; i++)
{
int outDegree = 0;
for (int j = 0; j < vertices; j++)
{
outDegree += adjacencyMatrix[i][j];
}
System.out.println("Vertex " + i + ": " + outDegree);
}
}
private static void displayAdjacencyMatrix(int[][] adjacencyMatrix, int vertices)
{
System.out.println("\nAdjacency Matrix:");
for (int i = 0; i < vertices; i++)
{
for (int j = 0; j < vertices; j++)
{
System.out.print(adjacencyMatrix[i][j] + " ");
}
System.out.println();
}
} }
Write a program that implements Prim’s algorithm to generate minimum cost spanning Tree.
import java.util.Scanner;
public class lab18
{
public static void main(String[] args)
{
int w[][]=new int[10][10];
int n,i,j,s,k=0;
int min;
int sum=0;
int u=0,v=0;
int flag=0;
int sol[]=new int[10];
System.out.println("Enter the number of vertices");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(i=1;i<=n;i++)
sol[i]=0;
System.out.println("Enter the weighted graph");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=sc.nextInt();
System.out.println("Enter the source vertex");
s=sc.nextInt();
sol[s]=1;
k=1;
while (k<=n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(sol[i]==1&&sol[j]==0)
if(i!=j&&min>w[i][j])
{
min=w[i][j];
u=i;
v=j;
}
sol[v]=1;
sum=sum+min;
k++;
System.out.println(u+"->"+v+"="+min);
}
for(i=1;i<=n;i++)
if(sol[i]==0)
flag=1;
if(flag==1)
System.out.println("No spanning tree");
else
System.out.println("The cost of minimum spanning tree is"+sum);
sc.close();
}}
Write a program that implements Kruskal’s algorithm to generate minimum cost
spanning tree.

import java.util.Scanner;
public class lab19
{
int parent[]=new int[10];
int find(int m)
{
int p=m;
while(parent[p]!=0)
p=parent[p];
return p;
}

void union(int i,int j)


{
if(i<j)
parent[i]=j;
else
parent[j]=i;
}

void krkl(int[][]a, int n)


{
int u=0,v=0,min,k=0,i,j,sum=0;
while(k<n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(a[i][j]<min&&i!=j)
{
min=a[i][j];
u=i;
v=j;
}
i=find(u);
j=find(v);
if(i!=j)
{
union(i,j);
System.out.println("("+u+","+v+")"+"="+a[u][v]);
sum=sum+a[u][v];
k++;
}
a[u][v]=a[v][u]=99;
}
System.out.println("The cost of minimum spanning tree = "+sum);
}
public static void main(String[] args)
{
int a[][]=new int[10][10];
int i,j;
System.out.println("Enter the number of vertices of the graph");
Scanner sc=new Scanner(System.in);
int n;
n=sc.nextInt();

System.out.println("Enter the wieghted matrix");


for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt();
lab19 k=new lab19();
k.krkl(a,n);
sc.close();
}
}

You might also like