Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

NIE Institute of Technology, Mysuru

Department of Computer Science and Engineering

DESIGN AND ANALYSIS OF ALGORITHMS


(INTEGRATED)

Course Code : 21CS42

Prepared by :

Mr Gowtham M Ms Sheeban E Tamanna


Asst. Professor Dept of CSE Asst. Professor Dept of CSE
NIEIT, Mysuru NIEIT, Mysuru
Programs
1) Sort a given set of n integer elements using Selection Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to sort.
Plot a graph of the time taken versus n. The elements can be read from a file or can be
generated using the random number generator. Demonstrate using C++/Java how the brute
force method works along with its time complexity analysis: worst case, average case and
best case.

import java.util.Random;
public class selectionSort {

public static void main(String[] args) {


Random random = new Random();
int [] array = new int[10];
for(int i = 0; i<10; i++) {
array[i] = random.nextInt(100);
}
System.out.println("The array elements before sorting is");
for (int i = 0; i<10; i++) {
System.out.print(" "+array[i]);
}
for(int i=0; i<10; i++) {
int minIndex = i;
for(int j=i+1; j<10; j++) {
if(array[j] < array[minIndex]) {
minIndex = j;
}
}
int temp=array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
System.out.println("\nThe array elements after swapping is");
for (int i = 0; i<10; i++) {
System.out.print(" "+array[i]);
}

2) Sort a given set of n integer elements using Quick Sort method and compute its
time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus n. The elements can be read from a file or
can be generated using the random number generator. Demonstrate using C++/Java
how the divide-and-conquer method works along with its time complexity analysis:
worst case, average case and best case.

import java.util.Scanner;
import java.util.Random;

public class qsort


{
int Partition(int a[],int low,int high)
{
int i,j,temp,key;

key=a[low];
i=low+1;
j=high;

while(true)
{
while(i < high && key >= a[i])
i++;
while(key < a[j])
j--;

if(i<j) // exchange ith and jth elements


{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else // exchange key and jth elements
{
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j; // returns the position of key
}
}//end of while
}//end of Paritition method

void QuickSort(int a[],int low,int high)


{
int j;
if(low<high)
{
j=Partition(a,low,high);
QuickSort(a,low,j-1);
QuickSort(a,j+1,high);
}
}

public static void main(String args[])


{
Random r = new Random();
final int MAX = 10000;
int[] a = new int[MAX];
qsort obj = new qsort();
int n=0,i=0;

Scanner input = new Scanner(System.in);


System.out.print("\n Enter the number of elements : ");
n=input.nextInt();

for(i=0;i<n;i++)
{
a[i] = r.nextInt(1000);//for random number inputs
System.out.print("\n Elements to be sorted \n");
System.out.print(a[i]+"\t");
}

long stime=0, etime=0;


stime = System.nanoTime();

obj.QuickSort(a,0,n-1);

etime = System.nanoTime();

System.out.print("\n The sorted elements are \n");


for(i=0;i<n;i++)
System.out.print(a[i]+"\t");

long Tcomplexity = etime - stime;


System.out.println("\nTime Complexity for n = " + n + " is: " + (double) Tcomplexity
/ 1000000 + " msec");
input.close();
}//end of main method
}//end of QSort class

3) Sort a given set of n integer elements using Merge Sort method and
compute its time complexity. Run the program for varied values of n> 5000,
and record the time taken to sort. Plot a graph of the time taken versus n. The
elements can be read from a file or can be generated using the random
number generator. Demonstrate using C++/Java how the divide-and-conquer
method works along with its time complexity analysis: worst case, average
case and best case.

import java.util.Random;
import java.util.Scanner;

public class mergesort {

void msort(int a[], int low, int high)


{
int mid;
if(low<high)
{
mid=(low+high)/2;
msort(a,low,mid); //left array
msort(a,mid+1,high); //right array
merge(a,low,mid,high);
}

void merge(int a[], int low, int mid, int high)


{
int i,j,k;
int[] b=new int[10000];
i=low; //left array with h value low to mid
j=mid+1; //right array with j value mid+1 to high
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]<a[j]) //compare the elements in subarray and copy smallest element in the array
{
b[k]=a[i];
k=k+1;
i=i+1;
}
else
{
b[k]=a[j];
k=k+1;
j=j+1;
}
}

while(i<=mid)//copy the remaining elements into the new array


{
b[k]=a[i];
k=k+1;
i=i+1;
}

while(j<=high)
{
b[k]=a[j];
k=k+1;
j=j+1;
}

for(i=low;i<=k-1;i++) //copying resultant array into original array


a[i]=b[i];

public static void main(String[] args) {


// TODO Auto-generated method stub
int a[]= new int[100000];
Scanner in = new Scanner(System.in);
long start, end;
mergesort m = new mergesort();

System.out.println("MERGE SORT PROGRAM");


System.out.println("Enter the number of elements to be sorted");
int n = in.nextInt();
Random rand= new Random();
for(int i=0;i<n;i++)
a[i]=rand.nextInt(100);

System.out.println("Array elements to be sorted are");


for(int i=0; i<n; i++)
System.out.print(a[i]+" ");

start=System.nanoTime();
m.msort(a,0,n-1);
end=System.nanoTime();
System.out.println("\nThe sorted elements are");
for(int i=0; i<n; i++)
System.out.print(a[i]+" ");

System.out.println("\nThe time taken to sort is "+(end-start)+"ns");


}

4) To solve Knapsack problem using Greedy method.

import java.util.Scanner;

public class Lab6B {


public static void main(String[] args) {
float w[]=new float[10],p[]=new float[10];
float ratio[]=new float[10];
Scanner in = new Scanner(System.in);
int i;
System.out.println("********* KNAPSACK PROBLEM *******");
System.out.println("Enter the total number of items: ");
int n = in.nextInt();
System.out.println("Enter the weight of each item: ");
for(i=1;i<=n;i++)
w[i] = in.nextFloat();
System.out.println("Enter the profit of each item: ");
for(i=1;i<=n;i++)
p[i] = in.nextFloat();
System.out.println("Enter the knapsack capacity: ");
int m= in.nextInt();
for(i=1;i<=n;i++)
ratio[i]=p[i]/w[i];
System.out.println("Information about knapsack problem are");
System.out.println("Capacity = "+m);
displayinfo(n,w,p,ratio);
knapsack(m,n,w,p);
System.out.println("*************************************");
}
}
static void displayinfo(int n,float w[],float p[],float ratio[]){
System.out.println("ITEM\tWEIGHT\tPROFIT\tRATIO(PROFIT/WEIGHT)");
for(int i=1; i<=n; i++)
System.out.println(i+"\t"+w[i]+"\t"+p[i]+"\t"+ratio[i]);
}
static void knapsack(int u,int n,float w[],float p[]){
float x[]=new float[10],tp=0;
int i;
for(i=1; i<=n; i++)
x[i]=0;
for(i=1; i<=n; i++){
if(w[i]>u)
break;
else{
x[i]=1;
tp=tp+p[i];
u=(int) (u-w[i]);
}
}
if(i<n)
x[i]=u/w[i];
tp=tp+(x[i]*p[i]);
System.out.println("\nThe result is = ");
for(i=1; i<=n; i++)
System.out.print("\t"+x[i]);
System.out.println("\nMaximum profit is = "+tp);
}
}

5) To find shortest paths to other vertices from a given vertex in a weighted


connected graph, using Dijkstra's algorithm.

package lab7;

import java.util.Scanner;

public class dijkstra {

int d[]=new int[10];


int p[]=new int[10];
int visited[]=new int[10];

public void dijk(int[][]a, int s, int n)


{
int u=-1,v,i,j,min;
for(v=1;v<=n;v++)
{
d[v]=999;
p[v]=-1;
}

d[s]=0;

for(i=1;i<=n;i++) //perform relaxation operation n times


{
min=999;
for(j=1;j<=n;j++)
{
if(d[j]<min && visited[j]==0) //select a vertex with minimum weight take that as u
{ // and also make that vertex as visited vertex
min=d[j];
u=j;
}
}
visited[u]=1;

for(v=1;v<=n;v++)
{
if((d[u]+a[u][v]<d[v]) && (u!=v) && visited[v]==0)
{
d[v]=d[u]+a[u][v]; //from the visited vertex u, relax the other vertices
p[v]=u; //and for the relaxed vertices v, make the parent vertex as u
}
}
}
}

void path(int v, int s)


{
if(p[v]!=-1)
path(p[v],s);
System.out.print("->"+v+" ");
}
void display(int s, int n)
{
int i;
for(i=1; i<=n; i++)
{
path(i,s);
System.out.print("="+d[i]+" ");
System.out.println();
}
}

public static void main(String[] args) {


int a[][]=new int[10][10];
int i,j,n,s;
System.out.println("Enter the number of vertices");
Scanner sc= new Scanner(System.in);
n=sc.nextInt();

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


for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt();

System.out.println("Enter the source vertex");


s=sc.nextInt();

dijkstra dj = new dijkstra();


dj.dijk(a,s,n);

System.out.println("The shortest path between source "+s+ " to remaining vertices are");
dj.display(s,n);

sc.close();
}
}

6) To find Minimum Cost Spanning Tree of a given connected undirected graph


using Kruskal's algorithm. Use Union-Find algorithms in your program.

package lab8;

import java.util.Scanner;
public class kruskal {

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 kruskals(int[][]a, int n)


{
int u=0,v=0,min,k=0,i,j,sum=0;

while(k<n-1)
{
min=999;
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]=999;
}
System.out.println("The cost of minimum spanning tree = "+sum);
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int a[][]=new int[10][10];
int i,j,n;

System.out.println("Enter the number of vertices");


n=sc.nextInt();

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


for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
a[i][j] = sc.nextInt();

System.out.println("Entered weighted matrix");


for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
System.out.print(a[i][j]+"\t");

System.out.println("");
}
kruskal k = new kruskal();
k.kruskals(a,n);

sc.close();
}

7) To find Minimum Cost Spanning Tree of a given connected undirected


graph using Prim's algorithm.

package lab9;

import java.util.Scanner;

public class prims {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int weight[][]=new int[10][10];
int n,i,j,source,vertex=0;
int min, sum=0,u=0,v=0;
int visited[]=new int [10];

System.out.println("Enter the number of vertices");


n=sc.nextInt();

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


visited[i]=0;

System.out.println("Enter the weighted graph/ cost matrix");


for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
weight[i][j] = sc.nextInt();
System.out.println("Enter the source vertex");
source=sc.nextInt();

visited[source]=1; //Visited

vertex=1;

while(vertex<=n-1)
{
min=999;
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
if(visited[i]==1 && visited[j]==0)
if(i!=j && min>weight[i][j])
{
min=weight[i][j]; //Minimum cost
u=i; //Source
v=j; //Destination

}
visited[v]=1; //visited
sum=sum+min;
vertex++;
System.out.println(u+"-->"+v+"="+min);
}

System.out.println("The cost of minimum spanning tree is "+sum);

sc.close();
}
}

8) Solve All-Pairs Shortest Paths problem using Floyd's algorithm.

package lab10a;

import java.util.Scanner;

public class floyds {

public static void main(String[] args) {


int a[][]=new int[10][10];
int i, j;
Scanner in = new Scanner(System.in);

System.out.println("***********FLOYD'SALGORITHM**********");
System.out.println("Enter the number of vertices: ");
int n = in.nextInt();

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


for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
a[i][j] = in.nextInt();

System.out.println("Entered adjacency matrix is: ");


for(i=1;i<=n;i++)
{
for(j=1; j<=n; j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}

floyd(a,n);

System.out.println("All pair shortest path matrix:");


for (i=1; i<=n; i++)
{
for (j=1; j<=n; j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}

}
static void floyd(int a[][],int n)
{
for (int k=1; k<=n; k++)
{
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
a[i][j] = Math.min(a[i][j], a[i][k] + a[k][j]);
}
}

9) Solve Travelling Sales Person problem using Dynamic programming.

package lab10b;

import java.util.Scanner;

public class lab10b {

static int tspdp(int c[][], int tour[], int start, int n)


{
int mintour[]=new int[10], temp[]=new int[10], mincost=999, ccost, i, j, k;

if(start == n-1)
return (c[tour[n-1]][tour[n]] + c[tour[n]][1]); //final cost

for(i=start+1; i<=n; i++) {


for(j=1; j<=n; j++)
temp[j] = tour[j];
temp[start+1] = tour[i];
temp[i] = tour[start+1];

if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost) {
mincost = c[tour[start]][tour[i]] + ccost;
for(k=1; k<=n; k++)
mintour[k] = temp[k];
}
}

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


tour[i] = mintour[i];
return mincost;
}

public static void main(String[] args) {

int c[][]=new int[10][10], tour[]=new int[10];


Scanner in = new Scanner(System.in);
int i, j,cost;

System.out.println("**** TSP DYNAMIC PROGRAMMING *******");

System.out.println("Enter the number of cities: ");


int n = in.nextInt();

if(n==1)
{
System.out.println("Path is not possible");
System.exit(0);
}

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


for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
c[i][j] = in.nextInt();

System.out.println("The entered cost matrix is");


for(i=1;i<=n;i++) {
for(j=1;j<=n;j++) {
System.out.print(c[i][j]+"\t");
}
System.out.println();
}

for(i=1;i<=n;i++)
tour[i]=i; //tour of every node is itself in the beginning

cost = tspdp(c, tour, 1, n);

System.out.println("The optimal tour is ");


for(i=1;i<=n;i++)
System.out.print(tour[i]+"->");
System.out.println("1");
System.out.println("The accurate mincost is "+cost);
System.out.println("******* ************* ***************");

}
}
10) Solve 0/1 Knapsack problem using Dynamic Programming method.
/* A Naive recursive implementation of 0-1 Knapsack problem */
class Knapsack {

// A utility function that returns maximum of two integers


s static int max(int a, int b) { return (a > b) ? a : b; }

// Returns the maximum value that can


// be put in a knapsack of capacity W
static int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;

// If weight of the nth item is more


// than Knapsack capacity W, then
// this item cannot be included in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);

// Return the maximum of two cases:


// (1) nth item included
// (2) not included
else
return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}

// Driver program to test above function


public static void main(String args[])
{
int val[] = new int[] { 60, 100, 120 };
int wt[] = new int[] { 10, 20, 30 };
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}

11) Design and implement C++/Java Program to find a subset of a given set S =
{Sl, S2,…, Sn} of n positive 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}. Display a suitable message, if the given problem instance
doesn't have a solution.

package lab11;

import java.util.Scanner;

public class subset {


static int c=0;
public static void main(String[] args) {
int w[]=new int[10];
int n, d, i, sum=0;
int x[]=new int[10];
Scanner in=new Scanner(System.in);

System.out.println("********** SUBSET PROBLEM ************");


System.out.println("Enter the number of elements: ");
n=in.nextInt();

System.out.println("Enter the elements in increasing order");


for(i=0;i<n;i++)
w[i]=in.nextInt();
System.out.println("Enter the value of d: ");
d=in.nextInt();

for(i=0;i<n;i++)
sum=sum+w[i];

System.out.println("SUM ="+sum);

if(sum < d || w[0] > d)


{
System.out.println("Subset is not possible ! ");
System.out.println("********** *********** *************");
System.exit(0);
}

subsetproblem(0,0,sum,x,w,d);

if(c==0)
System.out.println("Subset is not possible ! ");
System.out.println("\n********** ********* *************");
}

static void subsetproblem(int cs, int k, int r,int x[],int w[],int d)


{
x[k] = 1;
if(cs+w[k] == d)
{
c++;
System.out.print("\nSolution "+c+" is {");
for(int i=0;i<=k;i++)
if(x[i] == 1)
{
System.out.print(w[i]+" ");
}
System.out.print("}");
}
else if((cs + w[k] + w[k+1]) <= d)
subsetproblem(cs + w[k], k+1, r-w[k],x,w,d);

if((cs + r - w[k]) >= d && (cs + w[k+1]) <= d)


{
x[k] = 0;
subsetproblem(cs, k+1, r-w[k],x,w,d);
}
}
}

12) Design and implement C++/Java Program to find all Hamiltonian Cycles in
a connected undirected Graph G of n vertices using backtracking principle.

import java.util.Scanner;
public class hamiltonial
{
static int n;
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of vertices:");
n=in.nextInt();
int graph[][]=new int[10][10];
System.out.println("Enter the adjacency matrix:");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
graph[i][j]=in.nextInt();
System.out.println("Entered matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(graph[i][j]+"\t");
System.out.println();
}
hamcycle(graph);
System.out.println("***************************");
}

static void printsol(int path[])


{
System.out.println("Solution exists");
System.out.println("following is one cycle");
for(int i=0;i<n;i++)
System.out.print(path[i]+" ");
System.out.println(path[0]);
}

static boolean issafe(int v,int graph[][],int path[],int pos)


{
if(graph[path[pos-1]][v]==0)
return false;
for(int i=0;i<pos;i++)
if(path[i]==v)
return false;
return true;
}

static boolean hamcycleutil(int graph[][],int path[],int pos)


{
if(pos==n)
{
if(graph[path[pos-1]][path[0]]==1)
return true;
else
return false;
}
for(int v=1;v<n;v++)
{
if(issafe(v,graph,path,pos))
{
path[pos]=v;
if(hamcycleutil(graph,path,pos+1) == true)
return true;
path[pos]=-1;
}
}
return false;
}

static boolean hamcycle(int graph[][])


{
int path[]=new int[n+1];
for(int i=0;i<n;i++)
path[i]=-1;
path[0]=0;
if(hamcycleutil(graph,path,1) == false)
{
System.out.println("Solution does not exist");
return false;
}
printsol(path);
return true;
}
}

You might also like