Complete the code to declare the Job structure with id and deadline fields.
typedef struct Job {
int id;
int [1];
} Job;The field to store the deadline of a job is named deadline.
Complete the code to sort jobs by their deadline in ascending order.
int compareJobs(const void *a, const void *b) {
Job *jobA = (Job *)a;
Job *jobB = (Job *)b;
return jobA->[1] - jobB->[1];
}Sorting by deadline ensures jobs with earlier deadlines come first.
Fix the error in the code to schedule jobs within their deadlines using a greedy approach.
int scheduleJobs(Job jobs[], int result[], int n) {
int slot[n];
for (int i = 0; i < n; i++)
slot[i] = 0;
for (int i = 0; i < n; i++) {
for (int j = jobs[i].deadline - 1; j >= 0; j--) {
if (slot[j] == [1]) {
result[j] = i;
slot[j] = 1;
break;
}
}
}
return 0;
}The slot array uses 0 to indicate a free slot and 1 for occupied. We check if slot[j] == 0 to find a free slot.
Fill both blanks to print the scheduled jobs in order.
void printSchedule(Job jobs[], int result[], int n) {
printf("Scheduled jobs: ");
for (int i = 0; i < n; i++) {
if (result[i] != [1]) {
printf("%d ", jobs[result[i]].[2]);
}
}
printf("\n");
}We check if result[i] is not -1 (meaning a job is scheduled) and print the job's id.
Fill all three blanks to initialize the result array with -1 and sort jobs by deadline.
void initializeAndSort(Job jobs[], int n, int result[]) {
for (int i = 0; i < n; i++) {
result[i] = [1];
}
qsort(jobs, n, sizeof(Job), [2]);
}
int compareByDeadline(const void *a, const void *b) {
Job *jobA = (Job *)a;
Job *jobB = (Job *)b;
return jobA->[3] - jobB->[3];
}We initialize result with -1 to mark empty slots, use compareByDeadline for sorting, and compare the deadline field.