Skip to content

Instantly share code, notes, and snippets.

@GitEliteNovice
Last active May 22, 2019 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitEliteNovice/de12179083fcf3a6fc6802f624b27433 to your computer and use it in GitHub Desktop.
Save GitEliteNovice/de12179083fcf3a6fc6802f624b27433 to your computer and use it in GitHub Desktop.
Greedy Knapsack
{
for i=1 to n //step1
{
compute pi/wi; //step2
// form 1 to n we have compute above code ---- O(n) (tim taken , since it runs n times)
}
sort objects in non- increasing order p/w; //step3
// if i have n objects and i have to sort them, then
best sorting algorithm (compasion base sorting algo) is merge sort. -- O(nlogn) (time take for merge sort)
for i=1 to n //step4
{
if(m>0 && wi<=m) //step5
m = m - wi; //step6
P = P + pi; //step7
else //step8
break; //step9
}
// for above code we have iterate from 1 to on sorted list -- O(n) (time taken)
if(m>0) //step10
{
P=P+ pi*(m/wi); //step11
// this step will take constantant time so -- O(1) (time taken)
}
SO we total time taken will be = O(n) + O(nlogn) + O(n) +O(1)
so time complexity will be = O(nlogn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment