fractional knapsack problem in c

Here is an implementation of the fractional knapsack problem in C:

#include<stdio.h>
#include<stdlib.h>

typedef struct {
    int weight;
    int value;
    float ratio;
} Item;

int compare(const void a, const void b) {
    Item itemA = (Item )a;
    Item itemB = (Item )b;
    return itemB->ratio - itemA->ratio;
}

float fractionalKnapsack(int capacity, Item items[], int n) {
    qsort(items, n, sizeof(Item), compare);

    int currentWeight = 0;
    float finalValue = 0.0;

    for (int i = 0; i < n; i++) {
        if (currentWeight + items[i].weight <= capacity) {
            currentWeight += items[i].weight;
            finalValue += items[i].value;
        } else {
            int remainingWeight = capacity - currentWeight;
            finalValue += items[i].ratio * remainingWeight;
            break;
        }
    }

    return finalValue;
}

int main() {
    int capacity = 50;
    Item items[] = {
        {10, 60, 0.0},
        {20, 100, 0.0},
        {30, 120, 0.0}
    };
    int n = sizeof(items) / sizeof(items[0]);

    for (int i = 0; i < n; i++) {
        items[i].ratio = (float) items[i].value / items[i].weight;
    }

    float maxValue = fractionalKnapsack(capacity, items, n);
    printf("Maximum value we can obtain = %.2f", maxValue);

    return 0;
}

This implementation uses a structure Item to represent each item in the knapsack. The compare function is used as a comparator for sorting the items based on their value-to-weight ratio in descending order. The fractionalKnapsack function implements the fractional knapsack algorithm, which iterates through the sorted items and adds them to the knapsack until the capacity is reached. If an item cannot be fully added, a fraction of it is added based on the remaining capacity. The main function initializes the items and their ratio, calls the fractionalKnapsack function, and prints the maximum value that can be obtained.

Please note that this is just one possible implementation of the fractional knapsack problem in C, and there may be other approaches or variations depending on specific requirements.