#include <stdio.h>
#include <stdlib.h>
typedef struct Job {
int id;
int deadline;
int profit;
} Job;
// Compare function for qsort to sort jobs by profit descending
int compare(const void *a, const void *b) {
Job *jobA = (Job *)a;
Job *jobB = (Job *)b;
return jobB->profit - jobA->profit;
}
// Function to find max deadline
int findMaxDeadline(Job jobs[], int n) {
int max = 0;
for (int i = 0; i < n; i++) {
if (jobs[i].deadline > max) {
max = jobs[i].deadline;
}
}
return max;
}
// Job Scheduling function
void jobScheduling(Job jobs[], int n) {
// Sort jobs by profit descending
qsort(jobs, n, sizeof(Job), compare);
int maxDeadline = findMaxDeadline(jobs, n);
// Initialize time slots to -1 (free)
int *slots = (int *)malloc(maxDeadline * sizeof(int));
for (int i = 0; i < maxDeadline; i++) {
slots[i] = -1;
}
int totalProfit = 0;
int countJobs = 0;
// Iterate over jobs
for (int i = 0; i < n; i++) {
// Find a free slot for this job, starting from last possible slot
for (int j = jobs[i].deadline - 1; j >= 0; j--) {
if (slots[j] == -1) {
slots[j] = jobs[i].id; // Assign job id to slot
totalProfit += jobs[i].profit;
countJobs++;
break; // Move to next job
}
}
}
// Print scheduled jobs in order of slots
printf("Scheduled Jobs in slots:\n");
for (int i = 0; i < maxDeadline; i++) {
if (slots[i] != -1) {
printf("Slot %d: Job %d\n", i + 1, slots[i]);
} else {
printf("Slot %d: Free\n", i + 1);
}
}
printf("Total jobs scheduled: %d\n", countJobs);
printf("Total profit: %d\n", totalProfit);
free(slots);
}
int main() {
Job jobs[] = {
{1, 2, 20},
{2, 2, 15},
{3, 1, 10},
{4, 3, 5},
{5, 3, 1}
};
int n = sizeof(jobs) / sizeof(jobs[0]);
jobScheduling(jobs, n);
return 0;
}
qsort(jobs, n, sizeof(Job), compare);
sort jobs by profit descending to prioritize high profit jobs
for (int j = jobs[i].deadline - 1; j >= 0; j--) {
search for latest free slot before job deadline
totalProfit += jobs[i].profit;
add job profit to total
increment count of scheduled jobs
stop searching slots after scheduling job
Scheduled Jobs in slots:
Slot 1: Job 2
Slot 2: Job 1
Slot 3: Job 4
Total jobs scheduled: 3
Total profit: 40