0% found this document useful (0 votes)
3 views

Lab 4

lab task

Uploaded by

imransarker.web
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lab 4

lab task

Uploaded by

imransarker.web
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lab no: 04

Lab Name: Implement max heap, heapify and fractional knapsack problem using greedy
programming

Max heap and heapify: A max heap is a complete binary tree in which the value of
each node is greater than or equal to the values of its children, ensuring that the largest
element is always at the root. This property makes max heaps useful for implementing
priority queues and efficient sorting algorithms like heapsort. The process of maintaining
or building this structure is called heapify. Heapify can be performed in two ways: "up-
heapify" (or bubble-up) which is used when a new element is added to the heap,
ensuring the heap property is maintained by moving the new element up the tree, and
"down-heapify" (or bubble-down) which is used when the root element is removed or
replaced, ensuring the heap property is maintained by moving the new root element
down the tree to its correct position. The time complexity of heapify operations is O(log
n), where n is the number of nodes in the heap.

Algorithm:

Alg: MAX-HEAPIFY(A, i, n)
1. l ← LEFT(i)
2. r ← RIGHT(i)
3. if l ≤ n and A[l] > A[i]
4. then largest ←l
5. else largest ←i
6. if r ≤ n and A[r] > A[largest]
7. then largest ←r
8. if largest ← i
9. then exchange A[i] ↔ A[largest]
10. MAX-HEAPIFY(A, largest, n)

Max heap algorithm:

Alg: BUILD-MAX-HEAP(A)
1. n = length[A]
2. for i ← ⌊n/2⌋ down to 1
3. do MAX-HEAPIFY(A, i, n)
Code:
#include<iostream>
using namespace std;

void maxheapify(int a[], int i, int n)


{
int j, temp;
temp = a[i];
j = 2 * i;

while(j<=n)
{
if (j<n && a[j+1] > a[j])
j = j+1;
if(temp>a[j])
break;
else if(temp<= a[j])
{
a[j/2] = a[j];
j = 2 *j;
}
a[j/2] =temp;
return;
}
}
void HeapSort(int a[], int n)
{
int i, temp;
for(i = n; i>= 2; i--)
{
temp = a[i];
a[i] = a[1];
a[1] = temp;
maxheapify(a, 1, i-1);
}
}
void build_Maxheap(int a[], int n)
{
int i;
for(i = n/2; i>=1; i--)
maxheapify(a, i, n);

}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
n++;
int arr[n];
for(i =1; i<n; i++)
{
cout<<"Enter element "<<i<<": ";
cin>>arr[i];
}

build_Maxheap(arr, n-1);
HeapSort(arr, n-1);
cout<<"\n Sorted data ";

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


{
cout<<"->"<<arr[i];
}
return 0;
}

Output for above code:


Fractional Knapsack problem: The fractional knapsack problem is a variation of the
classic knapsack problem, where the goal is to maximize the total value of items placed
into a knapsack with a given weight capacity. Unlike the 0/1 knapsack problem, where
items must be taken or left in their entirety, the fractional knapsack problem allows items
to be broken into smaller parts. Each item has a specific weight and value, and one can
take any fraction of an item. To solve this problem, a greedy algorithm is typically used:
items are first sorted by their value-to-weight ratio, and then added to the knapsack in
that order. The algorithm continues adding items until the knapsack is full, possibly
taking a fraction of the last item if necessary. This approach ensures the maximum total
value is achieved with a time complexity of O(n log n) for sorting the items and O(n) for
filling the knapsack, where n is the number of items.

Algorithm:

1. Initialize totalProfit ← 0
2. Initialize curWeight ← w
3. For i ← 1 to n
a. used[i] ← 0
4. While curWeight > 0
a. maxi ← -1
b. For i ← 1 to n
i. If used[i] = 0 and (maxi = -1 or (A[1][i] / A[0][i]) > (A[1][maxi] / A[0][maxi]))
1. maxi ← i
c. If maxi = -1
i. Break
d. used[maxi] ← 1
e. If curWeight ≥ A[0][maxi]
i. curWeight ← curWeight - A[0][maxi]
ii. totalProfit ← totalProfit + A[1][maxi]
f. Else
i. totalProfit ← totalProfit + (A[1][maxi] / A[0][maxi]) * curWeight
ii. curWeight ← 0
4. Return totalProfit
FKP code:
#include<iostream>
using namespace std;

int main()
{
int array[2][100], n, w, i, curw, used[100], maxi = -1, totalprofit = 0;

//input number of objects


cout << "Enter number of items: ";
cin >> n;

//input max weight of knapsack


cout << "Enter the weight(capacity) of the knapsack: ";
cin >> w;
cout << "Enter the weight and profit of each items: ";

/* Array's first row is to store weights


second row is to store profits */
for (i = 0; i < n; i++)
{
cin >> array[0][i] >> array[1][i];
}

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


{
used[i] = 0;
}

curw = w;
//loop until knapsack is full
while (curw >= 0)
{
maxi = -1;
//loop to find max profit object
for (i = 0; i < n; i++)
{
if ((used[i] == 0) && ((maxi == -1) || (((float) array[1][i]/ (float) array[0][i]) > ((float)
array[1][maxi]/ (float) array[0][maxi]))))
{
maxi = i;
}
}
used[maxi] = 1;

//decrease current wight


curw -= array[0][maxi];

//increase total profit


totalprofit += array[1][maxi];
if (curw >= 0)
{
cout << "\nAdded object " << maxi + 1 << " Weight: "
<< array[0][maxi] << " Profit: " << array[1][maxi]
<< " completely in the bag, Space left: " << curw;
}
else
{
cout << "\nAdded object " << maxi + 1 << " Weight: "
<< (array[0][maxi] + curw) << " Profit: "
<< (array[1][maxi] / array[0][maxi]) * (array[0][maxi]
+ curw) << " partially in the bag, Space left: 0"
<< " Weight added is: " << curw + array[0][maxi];
totalprofit -= array[1][maxi];
totalprofit += ((array[1][maxi] / array[0][maxi]) * (array[0][maxi]
+ curw));
}
}
//print total worth of objects filled in knapsack
cout << "\nBags filled with objects worth: " << totalprofit;
return 0;
}

}
Output for above code:

Conclusion: In implementing both the max heap and the fractional knapsack problem in C++,
you have efficiently solved classic optimization challenges. The max heap ensures the largest
element is always at the root, maintaining this property through efficient heapify operations. The
fractional knapsack problem is addressed using a greedy algorithm, allowing item division and
maximizing total value within a given weight capacity by sorting items based on their value-to-
weight ratio. These implementations demonstrate your proficiency in applying fundamental
algorithms to real-world problems.

You might also like