Greedy Algorithm - Shortest Job First (SJF) CPU Scheduling
Scheduling policy that selects the waiting process with the smallest execution time to execute next
// Input list of process execution times
const input = [4, 3, 7, 1, 2];
// Function to calculate the average waiting time using SJF
function averageWaitingTimeSJF(processTimes) {
// Sort the process times in ascending order
const sortedTimes = processTimes.slice().sort((a, b) => a - b);
let totalWaitingTime = 0;
let accumulatedTime = 0;
// Calculate total waiting time
for (let i = 0; i < sortedTimes.length - 1; i++) {
accumulatedTime += sortedTimes[i];
totalWaitingTime += accumulatedTime;
}
// Calculate average waiting time
const averageWaitingTime = totalWaitingTime / sortedTimes.length;
return averageWaitingTime;
}
// Get the average waiting time
const avgWaitingTime = averageWaitingTimeSJF(input);
console.log('Average Waiting Time:', avgWaitingTime);
// output 4
Time Complexity: O(n) + nlogn (Sort+ Iteration)
Space Complexity: O(1) (Just tampering the data)
Thank you for reading!