Design and Analysis of Algorithms Lab
Design and Analysis of Algorithms Lab
COLLEGEOFENGINEERINGANDTECHNOLOGY,
BAMBHORIPOSTBOXNO.94,JALGAON– 425001. (M.S.)
Includedundersection2(f)&12(B)oftheUGCAct,1956
ISO 9001:2008 certified
PhoneNo.(0257)2258393,FaxNo.(0257)2258392
Website-www.sscoetjalgaon.ac.inEmail:
[email protected]
ISO9001:2008
DEPARTMENT OF COMPUTER
LaboratoryManuals
Subject:DesignandAnalysisofAlgorithmLab Academic
Year: 2023-24
Semester: VI
Todeveloptechnocratsasperindustrytechnicalneedsandsocialvalues.
MissionoftheDepartment
Toprovideconduciveenvironmenttoimparttechnicalknowledge
throughteaching,self-learningandskilldevelopmentprogramsto stand
1. CoreKnowledge
To provide students with Core Knowledge in mathematical, scientific and basic
engineeringfundamentalsnecessarytoformulate,analyzeandsolveengineering
problems and also to pursue advanced study or research.
2. Employment/ContinuingEducation
TotrainstudentswithgoodbreadthofknowledgeincoreareasofInformation
Technology and related engineering so as to comprehend engineering trade-
offs, analyze, design, and synthesize data and technical concepts to create
novel products and solutions for the real life problems.
3. ProfessionalCompetency
To inculcate in students to maintain high professionalism and ethical
standards, effective oral and written communication skills, to work as part of
teamsonmultidisciplinaryprojectsanddiverseprofessionalenvironments,and
relate engineering issues to the society, global economyand to emerging
technologies.
ProgramOutcomes(POs)
ITGraduateswillbeableto:
1. SoftwareSystem:Toapplysoftwareengineeringprinciplestostudy,
Analyze,design, implement, test and maintain software system.
2. Open Source Software: Demonstrate familiarity and practical
competencewithabroadrangeofprogramminglanguagesandopen
source platforms.
3. ComputerProficiency: Exhibitproficiency throughlatest technologies
indemonstratingtheabilityforworkefficacytotheindustry&society.
CourseOutcomes(COs)
SubjectName:DesignandAnalysisofAlgorithmsLab
UponsuccessfulcompletionoflabCourse,studentwillbeableto:
CO1:AnalyzeandImplementdivideandconquerapproach. CO2:
Implement dynamic programming approach
CO3:ImplementBranchandboundingapproach CO4:
Implement backtracking approach.
CO5:Implementgreedyalgorithmapproach
CO-PO-PSOMappingforDesignandAnalysisof Algorithms
Lab
CO1 3 3 2 2 2 1 1 2 1 2 3 2 1
CO2 3 3 2 2 2 1 1 1 1 2 1 2 3 2 1
CO3 3 3 2 2 2 1 1 1 1 2 1 2 3 2 1
CO4 3 3 2 2 2 1 1 1 1 2 1 2 3 2 1
CO5 3 3 2 2 2 1 1 1 1 2 1 2 3 2 1
Average 3 3 2 2 2 1 1 1 1 2 1 2 3 2 1
SSBT’sCollegeofEngineering&Technology,Bambhori,Jalgaon
DepartmentofComputer/ITEngineering
T.E.ITSemVI2
022-23
DesignandAnalysisof Algorithms
Lab
ListofExperiment
Sr.No. Title
1 Analyze&ImplementInsertionsortalgorithm
2 Analyze&ImplementQuicksortalgorithmusingDivideand Conquer
3 Implement0/1KnapsackusingDynamicProgramming
4 ImplementTravelSalesmanproblemusingBranchandBounding
5 ImplementgraphcoloringProblemusingbacktracking
6 ImplementjobsequencingAlgorithmusingGreedyAlgorithm
SSBT’sCollegeofEngineering&Technology,Bambhori,Jalgaon
DEPARTMENTOFINFORMATIONTECHNOLOGY
Class:T.E.
Roll
EXPERIMENT NO:
TITLE:Programforinsertionsort
AIM:Writeaprogramforsortingofnumbersusinginsertionsort algorithm.
Hardware/SoftwareRequirement:PC,WindowsXP/7,Ccompiler,Editor.
Theory
Insertionsortisasimplesortingalgorithmthatbuildsthefinalsortedarray(orlist)oneitem
atatime.Itismuchlessefficientonlargeliststhanmoreadvancedalgorithmssuchasquicksort,heap sort, or
merge sort. But it is very easy to implement and efficient for small data sets.
Best,worst,andaveragecases:
Thebestcaseinputisanarraythatisalreadysorted.Inthiscaseinsertionsorthasalinearrunningtime (i.e.,
O(n)).During each iteration, the first remaining element of the input is only compared with the right-
most element of the sorted subsection of the array.
Thesimplestworstcaseinputisanarraysortedinreverseorder.Thesetofallworstcaseinputsconsists of all
arrays where each element is the smallest or second-smallest of the elements before it. In these cases
everyiteration oftheinnerloop will scan and shift theentiresorted subsection ofthe array before inserting
the next element. This gives insertion sort a quadratic running time (i.e., O (n2)).
Theaveragecaseisalsoquadratic,whichmakesinsertionsortimpracticalforsortinglargearrays. However,
insertion sort is one of the fastest algorithms for sorting very small arrays.
HowtoimplementInsertionSort?
ReferenceBooks:-
1. Aho,“Design&AnalysisofComputerAlgorithms”,PearsonLPE.
2. RussMiller,“Algorithms:SequentialandParallel”,DreamtechPress.
3. Goodrich,“AlgorithmDesign:FoundationandAnalysis”,WileyIndia.
4. Grama,“AnIntrotoParallelComputing:Design&AnalysisofAlgorithms”,Second
Edition, Pearson LPE.
5. Baase,“ComputerAlgorithms:IntrotoDesign&Analysis”,ThirdEdition,PearsonLPE
QuestionsforViva:-
1. Explaininsertionsortwithexample.
2. Writeanpseudocodeforinsertionsort.
3. Explainbestcase,worstcaseandaverage caseof insertionsort.
NameofTeacher Sign
Miss. Mayuri Chandtratre
//Cprogramforinsertionsort
#include<math.h>#include
<stdio.h>
/*Functiontosortanarrayusinginsertionsort*/
inti,key,j;
key=arr[i];
j = i - 1;
/*Moveelementsofarr[0..i-1],thatare
while(j>=0&&arr[j]>key){
arr[j + 1] = arr[j];
j=j-1;
}
arr[j+1]=key;
}
//Autilityfunctiontoprintanarrayofsizen void
inti;
for(i=0;i <n;i++)
printf("%d",arr[i]);
printf("\n");
/*Driverprogramtotestinsertionsort*/ int
main()
intarr[]={12,11,13,5,6 };
intn=sizeof(arr)/ sizeof(arr[0]);
insertionSort(arr,n);
printArray(arr, n);
return0;
}
SSBT’sCollegeofEngineering&Technology,Bambhori,Jalgaon
DEPARTMENTOFINFORMATIONTECHNOLOGY
Name Class:T.E.
Roll
Date of Dateof
EXPERIMENT NO:
TITLE:ProgramforQuicksort.
AIM:Writeaprogramforquicksort ofnumbersusingdivideandconquerapproach.
Hardware/SoftwareRequirement:PC,WindowsXP/7,Ccompiler,Editor.
Theory
Itisalso calledpartition-exchangesort.Thisalgorithmdividesthelistintothreemainparts:
1. Elementsless thanthePivotelement
2. Pivotelement(Centralelement)
3. Elementsgreaterthanthepivotelement
HowtoimplementQuickSort?
Followingarethestepsinvolvedinquicksortalgorithm:
1. Afterselectinganelementaspivot,whichisthelastindexofthearrayinourcase,wedivide
thearrayforthefirsttime.
2. In quick sort, we call this partitioning. It is not simple breaking down of array into 2 sub
arrays,butincaseofpartitioning,thearrayelementsaresopositionedthatalltheelements
smallerthanthe pivotwill beontheleft sideofthepivot andall theelements greaterthan
thepivotwillbeontherightsideofit.
3. Andthepivotelementwillbeatitsfinalsortedposition.
4. Theelementstotheleftandright,maynotbesorted.
5. Thenwepicksubarrays,elementsontheleftofpivotandelementsontherightofpivot, and
weperformpartitioning onthembychoosingapivot inthesubarrays.
ComplexityAnalysisofQuickSort
WorstCaseTimeComplexity[Big-O]: O(n2)
BestCaseTimeComplexity[Big-omega]:O(n*logn)
Average Time Complexity [Big-theta]: O (n*log n)
Space Complexity: O (n*log n)
Result/Output:-
ReferenceBooks:-
1. Aho,“Design&AnalysisofComputerAlgorithms”,PearsonLPE.
2. RussMiller,“Algorithms:SequentialandParallel”,DreamtechPress.
3. Goodrich,“AlgorithmDesign:FoundationandAnalysis”,WileyIndia.
4. Grama,“AnIntrotoParallelComputing:Design&AnalysisofAlgorithms”,Second
Edition, Pearson LPE.
5. Baase,“ComputerAlgorithms:IntrotoDesign&Analysis”,ThirdEdition,PearsonLPE
QuestionsforViva:-
1. Explainquick sortwithexample.
2. Writeanpseudocodeforquicksort.
3. Explainbestcase,worstcaseandaveragecaseofquicksort.
NameofTeacher Sign
Miss. Mayuri Chandratre
ImplementingQuick SortAlgorithm
BelowwehaveasimpleCprogramimplementingtheQuicksort algorithm:
//simpleCprogramforQuickSort #
include <stdio.h>
/*
a[]isthearray,pisstartingindex,thatis0, and r is
the last index of array.
*/
voidquicksort(inta[], intp,intr)
{
if(p<r)
{
int q;
q=partition(a,p,r);
quicksort(a, p, q);
quicksort(a,q+1,r);
}
}
intmain()
{
int arr[] ={9, 7,5, 11, 12, 2,14, 3, 10, 6};
int n =sizeof(arr)/sizeof(arr[0]);
//callquickSortfunction
quickSort(arr, 0, n-1);
printf("Sortedarray:n");
printArray(arr, n);return
0;
}
SSBT’sCollegeofEngineering&Technology,Bambhori,Jalgaon
DEPARTMENTOFINFORMATIONTECHNOLOGY
Class:T.E.
Roll
EXPERIMENTNO:
TITLE:0/1Knapsackproblem
AIM:Writeaprogramtosolve0/1knapsackproblemusingdynamicprogramming approach.
Hardware/SoftwareRequirement:PC,WindowsXP/7,Ccompiler,Editor.
Theory
Definition of 0/1 knapsack problem is“Given a set of items, each with a weight and a
value,determinethenumberofeachitemtoincludeinacollectionsothat thetotalweightis less than
or equal to a given limit and the total value is as large as possible.”
Given weights and values of n items, put these items in a knapsack of capacity W to get
the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1]
and wt[0..n-1] which represent values and weights associated with n items respectively. Also
givenanintegerWwhichrepresentsknapsackcapacity,findoutthemaximumvaluesubsetof val[]
such that sum of the weights of this subset is smaller than or equal to W. You cannot break an
item, either pick the complete item, or don’t pick it (0-1 property).
A simple solution is to consider all subsets of items and calculate the total weight and
valueofallsubsets.ConsidertheonlysubsetswhosetotalweightissmallerthanW.Fromall such
subsets, pick the maximum value subset.
1) Optimal Substructure:
Toconsiderallsubsetsof items,therecanbetwocasesforeveryitem:(1)theitemisincluded in the
optimal subset, (2) not included in the optimal set.
Therefore,themaximumvaluethatcanbeobtainedfromnitemsismaxoffollowingtwo values.
1) Maximumvalueobtained byn-1items andWweight (excludingnth item).
2) Valueofnthitemplusmaximumvalueobtainedbyn-1itemsandWminusweightofthe nth item
(including nth item).
IfweightofnthitemisgreaterthanW,thenthenthitemcannotbeincludedandcase1isthe only
possibility.
2) OverlappingSub problems
Problemsareevaluatedagainandagain,thisproblemiscalledOverlappingSubproblem’sproperty.
TimeComplexity:
Result/Output:-
ReferenceBooks:-
1. Aho,“Design&AnalysisofComputerAlgorithms”,PearsonLPE.
2. RussMiller,“Algorithms:SequentialandParallel”,DreamtechPress.
3. Goodrich,“AlgorithmDesign:FoundationandAnalysis”,WileyIndia.
4. Grama,“AnIntrotoParallelComputing:Design&AnalysisofAlgorithms”,Second
Edition, Pearson LPE.
5. Baase,“ComputerAlgorithms:IntrotoDesign&Analysis”,ThirdEdition,PearsonLPE
QuestionsforViva:-
1. whatis0/1knapsackproblem?.
2. Explain0/1knapsackproblemwithexample.
NameofTeacher Sign
Miss. Mayuri Chandratre
//ADynamicProgrammingbasedsolutionfor0-1Knapsackproblem
#include<stdio.h>
//Autilityfunctionthatreturnsmaximumoftwointegers int
//ReturnsthemaximumvaluethatcanbeputinaknapsackofcapacityW int
int i, w;
intK[n+1][W+1];
//BuildtableK[][]inbottomupmanner for (i
= 0; i <= n; i++)
for(w=0; w<=W;w++)
if(i==0 ||w==0)
K[i][w]=0;
elseif(wt[i-1]<=w)
K[i][w]=max(val[i-1]+K[i-1][w-wt[i-1]],K[i-1][w]);
else
K[i][w]=K[i-1][w];
}
returnK[n][W];
intmain()
int W=50;
int n = sizeof(val)/sizeof(val[0]);
printf("%d",knapSack(W,wt,val,n));
return 0;
}
SSBT’sCollegeofEngineering&Technology,Bambhori,Jalgaon
DEPARTMENTOFINFORMATIONTECHNOLOGY
Class:T.E.
Roll
EXPERIMENT NO:
TITLE:Programfortravellingsalesmanproblem.
AIM:Writeaprogramfortravellingsalesmanproblemusingbranchandboundtechnique.
Hardware/SoftwareRequirement:PC,WindowsXP/7,Ccompiler,Editor.
Theory
Travellingsalesmanproblemconsistof“Givenasetofcitiesanddistancebetweeneverypair
ofcities,the problem is to findthe shortest possible tourthat visits everycityexactlyonce and returns to the
starting point.”
Branch and bound is an algorithm design paradigm which is generally used for solving
combinatorial optimization problems. These problems are typically exponential in terms of time
complexityandmayrequireexploringallpossiblepermutationsinworstcase.TheBranchandBound
Algorithm technique solves these problems relatively quickly.
HowtoimplementTravellingsalesman problem?
FollowingarethestepsinvolvedinTSP:
1. Createstatespacetreestartingfromrootnode.
2. Calculatecostofeachnodeandchild node.
3. Selectmostpromisingchildforfurtherexpansion(givesoptimalsolution)killremainingothernode of that
expansion.
4. Repeatstep3tillyoureachedtoagainstarting node.
Result/Output:-
ReferenceBooks:-
1. Aho,“Design&AnalysisofComputerAlgorithms”,PearsonLPE.
2. RussMiller,“Algorithms:SequentialandParallel”,DreamtechPress.
3. Goodrich,“AlgorithmDesign:FoundationandAnalysis”,WileyIndia.
4. Grama,“AnIntrotoParallelComputing:Design&AnalysisofAlgorithms”,Second
Edition, Pearson LPE.
5. Baase,“ComputerAlgorithms:IntrotoDesign&Analysis”,ThirdEdition,PearsonLPE
QuestionsforViva:-
1. ExplainTravellingsalesmanproblemwithexample.
2. Differentiatebetweendynamicandbranchandboundtechnique.
NameofTeacher Sign
Miss. Mayuri Chandratre
TRAVELINGSALESMANUSINGBRANCHANDBOUNDTECHNIQUE
#include<stdio.h>#include<co
nio.h>
inta[10][10],visited[10],n,cost=0;
voidget()
{
int i,j;
printf(“EnterNo.ofCities:“);
scanf(“%d”,&n);
printf(“\nEnterCostMatrix:\n”);
for( i=0;i<n;i++)
{
printf(“\nEnterElementsofRow#:%d\n”,i+1); for(
j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
visited[i]=0;
}
printf(“\n\nThecostlistis:\n\n”);
for( i=0;i<n;i++)
{
printf(“\n\n”);
for(j=0;j<n;j++)
printf(“\t%d”,a[i][j]);
}
}
voidmincost(intcity)
{
int i,ncity;
visited[city]=1;
printf(“%d–>”,city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf(“%d”,ncity+1);
cost+=a[city][ncity];
return;
}
mincost(ncity);
}
intleast(intc)
{
inti,nc=999;
intmin=999,kmin;
for(i=0;i<n;i++)
{
if((a[c][i]!=0)&&(visited[i]==0))
if(a[c][i]<min)
{
min=a[i][0]+a[c][i];
kmin=a[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
return nc;
}
voidput()
{
printf(“\n\nMinimumcost:”);
printf(“%d”,cost);
}
voidmain()
{
clrscr();
get();
printf(“\n\nThePathis:\n\n”);
mincost(0);
put();
getch();
}
Output
Input Sample:
No.ofNodes:6
Cost Matrix:
99 10 15 20 99 8
5 99 9 10 8 99
6 13 99 12 99 5
8 8 9 99 6 99
99 10 99 6 99 99
10 99 5 99 99 99
SSBT’sCollegeofEngineering&Technology,Bambhori,Jalgaon
DEPARTMENTOFINFORMATIONTECHNOLOGY
Class:T.E.
Roll
EXPERIMENT NO:
TITLE:Programforgraphcoloringproblem.
AIM:Writeaprogramforgraphcoloringproblemusingbacktrackingtechnique.
Hardware/SoftwareRequirement:PC,WindowsXP/7,Ccompiler,Editor.
Theory
Input:
1) A 2D array graph[V][V] where V is the numberof vertices in graph and graph[V][V] is adjacency
matrixrepresentationofthegraph.Avaluegraph[i][j]is1ifthereisadirectedgefromitoj,otherwise graph[i][j]
is 0.
2) Anintegerm whichisthemaximum numberofcolorsthat canbeused.
Output:
Anarraycolor[V]thatshouldhavenumbersfrom1tom.color[i]shouldrepresentthecolorassignedto the ith
vertex. The code should also return false if the graph cannot be colored with m colors.
BactrackingAlgorithm
Backtracking algorithmmakestheprocesstosolvetheproblemmoreefficientbyavoidingmuchbad
decision that needed to be made in the naive approach. We start by coloring a single vertex, then we
move to its adjacent vertex. We color it with that color which has not been used to color any of its
connected vertices. After coloring it we then move to its adjacent vertex which is uncolored. We repeat
the process until all vertices of the given graph are colored.
In case we find for a vertex that all its adjacent (connected) are colored with different colors andno color
is left to make it color different from them, then it means the given number of colors i.e „m‟, is
insufficient to color the graph. Hence we require more colors i.e bigger chromatic number.
Howtoimplementgraph coloringproblem?
FollowingarethestepsinvolvedinTSP:
1. Confirmwhetheritisvalidtocolorthevertexwithcurrentcolor?bycheckingwhetheranyofits adjacent
vertices are colored with the same color?
2. Ifyesthencolorit orelsetrywithanother color.
3. Ifnoothercolorisavailablethenbacktracki.eun-colorlastcoloredvertexandreturn false.
4. Aftereachcoloringcheckifallverticesarecoloredornot.Ifyesthenendtheprogramby returning
true, else continue.
5. Nowselectanyoneoftheuncoloredadjacentverticesofthecurrentcoloredvertexandrepeat the
whole process
Herebacktrackingmeanstostopfurtherrecursivecallsonadjacentverticesbyreturningfalse.In this
algorithm Step-2 (Continue) and Step-4 (backtracking) is causing the program to try
different color option.
Continue–tryadifferentcolorforcurrent vertex.
Backtrack–tryadifferentcolorforlastcoloredvertex.
Result/Output:-
ReferenceBooks:-
1. Aho,“Design&AnalysisofComputerAlgorithms”,PearsonLPE.
2. RussMiller,“Algorithms:SequentialandParallel”,DreamtechPress.
3. Goodrich,“AlgorithmDesign:FoundationandAnalysis”,WileyIndia.
4. Grama,“AnIntrotoParallelComputing:Design&AnalysisofAlgorithms”,Second
Edition, Pearson LPE.
5. Baase,“ComputerAlgorithms:IntrotoDesign&Analysis”,ThirdEdition,PearsonLPE
QuestionsforViva:-
1. Explaingraphcoloringproblemwithexample.
2. Whatisbacktracking?
NameofTeacher Sign
Miss. Mayuri Chandratre
Graphcoloring usingbacktracking
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
//Number of vertices
#definenumOfVertices4
//functionPrototypes
boolcanColorWith(int,int );
//0 -Green
//1 -Blue
charcolors[][30]={"Green","Blue"}; int
color_used = 2;
intcolorCount;
//Graphconnections
intgraph[numOfVertices][numOfVertices] ={{0,1,0,1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}};
typedef struct{
char name;
boolcolored;
int color;
} Vertex;
//VertexList
Vertex*vertexArray[numOfVertices];
boolsetColors(int idx){
intcolorIndex, unColoredIdx;
for(colorIndex=0;colorIndex<color_used;colorIndex++){
//Step-1:checkingvalidity
if(!canColorWith(colorIndex,idx))continue;//Step-2:Continue
//Step-2: coloring
vertexArray[idx]->color=colorIndex;
vertexArray[idx]->colored = true;
colorCount++;
//Step-5:Nextuncoloredvertex
while((unColoredIdx=hasUncoloredNeighbours(idx))!=-1){
if(setColors(unColoredIdx))
returntrue;
}
// Step-3 : Backtracking
vertexArray[idx]->color = -1;
vertexArray[idx]->colored =false;
return false;
}
//Functiontocheckwhetheritisvalidtocolorwithcolor[colorIndex] bool
canColorWith(int colorIndex, int vertex) {
Vertex*neighborVertex;
int i;
for(i=0;i<numOfVertices; i++){
//skippingifvertexarenotconnected
if(graph[vertex][i] == 0) continue;
neighborVertex=vertexArray[i];
if(neighborVertex->colored&&neighborVertex->color==colorIndex)
returnfalse;
}
returntrue;
}
intmain()
{
inti;
//CreatingVertex
VertexvertexA,vertexB,vertexC, vertexD;
vertexA.name='A';
vertexB.name='B';
vertexC.name='C';
vertexD.name='D';
vertexArray[0]=&vertexA;
vertexArray[1]=&vertexB;
vertexArray[2]=&vertexC;
vertexArray[3]=&vertexD;
for(i=0; i<numOfVertices;i++){
vertexArray[i]->colored =false;
vertexArray[i]->color = -1;
}
boolhasSolution=setColors(0); if
(!hasSolution)
printf("NoSolution");
else {
for(i=0;i<numOfVertices;i++){
printf("%c%s\n",vertexArray[i]->name,colors[vertexArray[i]->color]);
}
}
return0;
}
SSBT’sCollegeofEngineering&Technology,Bambhori,Jalgaon
DEPARTMENTOFINFORMATIONTECHNOLOGY
Class:T.E.
Roll
EXPERIMENT NO:
TITLE:Programforjob sequencing.
AIM:Writeaprogramforjobsequencingusinggreedyapproach.
Hardware/SoftwareRequirement:PC,WindowsXP/7,Ccompiler,Editor.
Theory
GreedyAlgorithm
Greedy algorithms build a solution part by part, choosing the next part in such a way, that it gives an
immediate benefit. This approach never reconsiders the choices taken previously. This approach is
mainlyusedtosolveoptimizationproblems.Greedymethodiseasytoimplementandquiteefficientin most of
the cases. Hence, we can say that Greedy algorithm is an algorithmic paradigm based on
heuristicthatfollowslocaloptimalchoiceateachstepwiththehopeoffindingglobaloptimalsolution.
Inmanyproblems,itdoesnotproduceanoptimalsolutionthoughitgivesanapproximate(nearoptimal) solution
in a reasonable time.
Howtoimplementjobsequencing problem?
Followingstepsareinvolvedinjobsequencingalgorithm,
1) Sortalljobsindecreasingorderofprofit.
2) Initializetheresult sequenceas firstjobinsortedjobs.
3) Dofollowingforremainingn-1 jobs
a) Ifthecurrentjobcanfitinthecurrentresultsequencewithoutmissingthedeadline, add
currentjob to the result. Else ignore the current job.
Result/Output:-
ReferenceBooks:-
1. Aho,“Design&Analysis ofComputerAlgorithms”,PearsonLPE.
2. RussMiller,“Algorithms:SequentialandParallel”,DreamtechPress.
3. Goodrich,“AlgorithmDesign:FoundationandAnalysis”,WileyIndia.
4. Grama,“AnIntrotoParallelComputing:Design&AnalysisofAlgorithms”,Second
Edition, Pearson LPE.
5. Baase,“ComputerAlgorithms:IntrotoDesign&Analysis”,ThirdEdition,PearsonLPE
QuestionsforViva:-
1. Explainjobsequencingwith example.
2. Whatisgreedyalgorithm?
NameofTeacher Sign
Miss. Mayuri Chandratre
//Programtofindthemaximumprofitjobsequencefromagivenarrayofjobswithdeadlinesand profits
#include<stdio.h>#def
ine MAX 100
typedefstructJob{ char
id[5];
intdeadline;
int profit;
}Job;
voidjobSequencingWithDeadline(Jobjobs[],intn);
int minValue(int x, int y) {
if(x<y)returnx;
returny;
}
intmain(void){
//variables
int i, j;
//jobswithdeadlineandprofit
Job jobs[5] = {
{"j1",2,60},
{"j2",1, 100},
{"j3",3,20},
{"j4",2,40},
{"j5",1,20},
};
//temp
Jobtemp;
//numberofjobs int
n = 5;
//sortthejobsprofitwiseindescendingorder for(i
= 1; i < n; i++) {
for(j = 0; j < n - i; j++) {
if(jobs[j+1].profit >jobs[j].profit) {
temp = jobs[j+1];
jobs[j+1]=jobs[j];
jobs[j] = temp;
}
}
}
printf("%10s%10s%10s\n","Job","Deadline","Profit");
for(i = 0; i < n; i++) {
printf("%10s%10i%10i\n",jobs[i].id,jobs[i].deadline,jobs[i].profit);
}
jobSequencingWithDeadline(jobs,n);
return 0;
}
voidjobSequencingWithDeadline(Jobjobs[],intn) {
//variables
int i, j, k,maxprofit;
//freetimeslots
inttimeslot[MAX];
//filledtime slots
intfilledTimeSlot=0;
//findmaxdeadlinevalue
int dmax = 0;
for(i = 0; i < n; i++) {
if(jobs[i].deadline>dmax){
dmax = jobs[i].deadline;
}
}
//freetimeslotsinitiallysetto-1[-1denotesEMPTY] for(i
= 1; i <= dmax; i++) {
timeslot[i]=-1;
}
printf("dmax:%d\n",dmax);
for(i = 1; i <= n; i++) {
k=minValue(dmax,jobs[i-1].deadline); while(k
>= 1) {
if(timeslot[k]==-1){
timeslot[k] = i-1;
filledTimeSlot++;
break;
}
k--;
}
//ifalltimeslotsarefilledthenstop
if(filledTimeSlot == dmax) {
break;
}
}
//required jobs
printf("\nRequiredJobs:"); for(i
= 1; i <= dmax; i++) {
printf("%s",jobs[timeslot[i]].id);
if(i < dmax) {
printf("-->");
}
}
//requiredprofit
maxprofit = 0;
for(i = 1; i <= dmax; i++)
{maxprofit+=jobs[timeslot[i]].profit;
}
printf("\nMaxProfit:%d\n",maxprofit);
}
Output
JobDeadline Profit j2
1 100
j1 2 60
j4 2 40
j3 3 20
j5 1 20
dmax:3
RequiredJobs:j2--> j1 ---- >j3
MaxProfit: 180