702782. First Come First Serve
Easy
Here is the blog post for the First Come First Serve problem:
First Come First Serve
Summary
The First Come First Serve (FCFS) scheduling algorithm is a simple and efficient method to allocate resources, such as CPU time or memory, in a system. The key concept involved is the order of arrival of processes requesting these resources.
Detailed Explanation
In FCFS, each process arrives at a certain time and waits for its turn to be executed. The algorithm executes the processes in the order they arrive. This means that the first process to arrive is executed first, then the second, and so on.
Here's a step-by-step breakdown of the solution:
- Read the input: Take an array of arrival times and burst times of processes.
- Sort the processes based on their arrival time.
- Initialize the current time as 0.
- Iterate over the sorted processes:
- If the process arrives at or after the current time, execute it and update the current time to the sum of the current time and the process's burst time.
- Repeat step 4 until all processes are executed.
Time complexity: O(n log n) due to sorting Space complexity: O(1)
Optimized Solutions
Java
public class FCFS {
public static void schedule(int[] arrivalTimes, int[] burstTimes) {
// Sort the processes based on their arrival time
for (int i = 0; i < arrivalTimes.length - 1; i++) {
for (int j = i + 1; j < arrivalTimes.length; j++) {
if (arrivalTimes[i] > arrivalTimes[j]) {
int tempArrival = arrivalTimes[i];
int tempBurst = burstTimes[i];
arrivalTimes[i] = arrivalTimes[j];
burstTimes[i] = burstTimes[j];
arrivalTimes[j] = tempArrival;
burstTimes[j] = tempBurst;
}
}
}
// Initialize the current time as 0
int currentTime = 0;
// Iterate over the sorted processes:
for (int i = 0; i < arrivalTimes.length; i++) {
if (arrivalTimes[i] >= currentTime) {
// Execute the process and update the current time
currentTime += burstTimes[i];
}
}
}
}