You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>

// Define a struct to represent a job


struct Job {
int id;
int arrivalTime;
int burstTime;
};

// Define a struct to represent a node in a linked list


struct Node {
struct Job job;
struct Node* next;
};

// Function to add a new job to the linked list, sorted by arrival time
void insertJob(struct Node** headRef, struct Job job) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->job = job;
newNode->next = NULL;

if (*headRef == NULL || (*headRef)->job.arrivalTime > job.arrivalTime) {


newNode->next = *headRef;
*headRef = newNode;
}
else {
struct Node* curr = *headRef;
while (curr->next != NULL && curr->next->job.arrivalTime <=
job.arrivalTime) {
curr = curr->next;
}
newNode->next = curr->next;
curr->next = newNode;
}
}

// Function to remove the first job from the linked list


void removeJob(struct Node** headRef) {
if (*headRef == NULL) {
return;
}

struct Node* temp = *headRef;


*headRef = (*headRef)->next;
free(temp);
}

// Function to simulate the CPU processing jobs using the SJF algorithm
void sjf(struct Node* head) {
int time = 0;

while (head != NULL) {


struct Node* curr = head;
struct Job shortestJob = head->job;

// Find the job with the shortest remaining burst time


while (curr != NULL) {
if (curr->job.burstTime < shortestJob.burstTime) {
shortestJob = curr->job;
}
curr = curr->next;
}

// Process the shortest job and update the time


printf("Processing Job %d from time %d to %d\n", shortestJob.id, time, time
+ shortestJob.burstTime);
time += shortestJob.burstTime;

// Remove the processed job from the linked list


removeJob(&head);
}
}

int main() {
// Define the job queue
struct Job jobQueue[] = {
{1, 0, 10},
{2, 1, 5},
{3, 2, 2},
{4, 3, 7}
};

// Initialize the linked list with the first job


struct Node* head = NULL;
insertJob(&head, jobQueue[0]);

// Add the remaining jobs to the linked list


for (int i = 1; i < sizeof(jobQueue)/sizeof(jobQueue[0]); i++) {
insertJob(&head, jobQueue[i]);
}

// Simulate the CPU processing the jobs using the SJF algorithm
sjf(head);

return 0;
}

You might also like