C CODE
C CODE
#include <stdio.h>
void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
{
largest = l;
}
if (r < n && arr[r] > arr[largest])
{
largest = r;
}
if (largest != i)
{
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i > 0; i--)
{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int n,i;
printf("Enter the size of the array: ");
scanf("%d",&n);
int a[n];
printf("Enter the array elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
heapSort(a, n);
printf("Sorted array is \n");
printArray(a, n);
return 0;
}
KNAPSACK
#include <stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity)
{
float tp = 0, u = capacity;
float x[n];
for (int i = 0; i < n; i++)
x[i] = 0;
for (int i = 0; i < n; i++)
{
if (weight[i] > u)
break;
x[i] = 1;
tp += profit[i];
u -= weight[i];
}
// If there is remaining capacity, take fraction of the next item
if (u > 0)
{
int i;
for (i = 0; i < n; i++)
{
if (x[i] == 0)
{
x[i] = u / weight[i];
tp += x[i] * profit[i];
break;
}
}
}
// Print the selected fractions
printf("Selected fractions: ");
for (int i = 0; i < n; i++)
printf("%.2f ", x[i]);
int main() {
int n;
printf("Enter the number of items: ");
scanf("%d", &n);
float capacity;
printf("Enter the knapsack capacity: ");
scanf("%f", &capacity);
// Swap ratio
temp = ratio[i];
ratio[i] = ratio[j];
ratio[j] = temp;
// Swap weight
temp = weight[i];
weight[i] = weight[j];
weight[j] = temp;
// Swap profit
temp = profit[i];
profit[i] = profit[j];
profit[j] = temp;
}
}
}
// Solve knapsack problem
knapsack(n, weight, profit, capacity);
return 0;
}