Greedy Algorithm - Shortest Job First (SJF) CPU Scheduling

// 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!
Subscribe to my newsletter
Read articles from Palak Bansal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Palak Bansal
Palak Bansal
Experienced Frontend Developer with a demonstrated history of working in the financial services industry along with having 5+ years of hands on professional experience efficiently coding websites and applications using modern HTML, CSS and Javascript along with their respective frameworks viz.Vue.JS, React.JS. Instituting new technologies and building easy to use and user-friendly websites is truly a passion of mine. I actively seek out new libraries and stay up-to-date on industry trends and advancements. Translated designs to frontend code along with streamlining existing code to improve site performance. Collaborated with UX designers and Back End Developers to ensure coherence between all parties. Also tested some feature prototypes for bugs and user experience.