Skip to content

Commit 750ecea

Browse files
committed
refactor: fix indexed list iteration
1 parent e3afbe8 commit 750ecea

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

src/main/java/com/thealgorithms/scheduling/SJFScheduling.java

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
import com.thealgorithms.devutils.entities.ProcessDetails;
44
import java.util.ArrayList;
5+
import java.util.Collection;
56
import java.util.Comparator;
7+
import java.util.Iterator;
68
import java.util.List;
79

810
/**
@@ -31,13 +33,24 @@ public void scheduleProcesses() {
3133
int size = processes.size();
3234
int time = 0;
3335
int executed = 0;
34-
int k = 0;
36+
37+
Iterator<ProcessDetails> processIterator = processes.iterator();
38+
39+
// This will track the next process to be checked for arrival time
40+
ProcessDetails nextProcess = null;
41+
if (processIterator.hasNext()) {
42+
nextProcess = processIterator.next();
43+
}
3544

3645
while (executed < size) {
37-
// Load arrived processes into ready queue
38-
while (k < size && processes.get(k).getArrivalTime() <= time) {
39-
ready.add(processes.get(k));
40-
k++;
46+
// Load all processes that have arrived by current time
47+
while (nextProcess != null && nextProcess.getArrivalTime() <= time) {
48+
ready.add(nextProcess);
49+
if (processIterator.hasNext()) {
50+
nextProcess = processIterator.next();
51+
} else {
52+
nextProcess = null;
53+
}
4154
}
4255

4356
ProcessDetails running = findShortestJob(ready);
@@ -58,7 +71,7 @@ public void scheduleProcesses() {
5871
* @return returns the process' with the shortest burst time OR NULL if there are no ready
5972
* processes
6073
*/
61-
private ProcessDetails findShortestJob(List<ProcessDetails> readyProcesses) {
74+
private ProcessDetails findShortestJob(Collection<ProcessDetails> readyProcesses) {
6275
return readyProcesses.stream().min(Comparator.comparingInt(ProcessDetails::getBurstTime)).orElse(null);
6376
}
6477

0 commit comments

Comments
 (0)