Skip to content

Commit 4bcddd3

Browse files
Add Preemptive Priority Scheduling Algorithm (TheAlgorithms#4323)
1 parent af80c80 commit 4bcddd3

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.thealgorithms.scheduling;
2+
3+
import java.util.*;
4+
5+
/**
6+
* Preemptive Priority Scheduling Algorithm
7+
* @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi)
8+
*/
9+
10+
class Process {
11+
String name;
12+
int arrivalTime;
13+
int burstTime;
14+
int priority;
15+
16+
public Process(String name, int arrivalTime, int burstTime, int priority) {
17+
this.name = name;
18+
this.arrivalTime = arrivalTime;
19+
this.burstTime = burstTime;
20+
this.priority = priority;
21+
}
22+
}
23+
24+
public class PreemptivePriorityScheduling {
25+
public static List<String> preemptivePriorityScheduling(List<Process> processes) {
26+
List<String> ganttChart = new ArrayList<>();
27+
PriorityQueue<Process> readyQueue = new PriorityQueue<>(Comparator.comparingInt(p -> - p.priority));
28+
29+
int currentTime = 0;
30+
31+
while (!processes.isEmpty() || !readyQueue.isEmpty()) {
32+
while (!processes.isEmpty() && processes.get(0).arrivalTime <= currentTime) {
33+
readyQueue.add(processes.remove(0));
34+
}
35+
36+
if (!readyQueue.isEmpty()) {
37+
Process currentProcess = readyQueue.poll();
38+
39+
ganttChart.add(currentProcess.name);
40+
currentProcess.burstTime--;
41+
42+
if (currentProcess.burstTime > 0) {
43+
readyQueue.add(currentProcess);
44+
}
45+
} else {
46+
ganttChart.add("Idle");
47+
}
48+
49+
currentTime++;
50+
}
51+
52+
return ganttChart;
53+
}
54+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.scheduling;
2+
3+
/**
4+
* Test Cases of Preemptive Priority Scheduling Algorithm
5+
* @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi)
6+
*/
7+
8+
import static org.junit.jupiter.api.Assertions.*;
9+
10+
import java.util.*;
11+
import org.junit.jupiter.api.Test;
12+
13+
class PreemptivePrioritySchedulingTest {
14+
15+
@Test
16+
void testPreemptivePriorityScheduling() {
17+
// Arrange
18+
List<Process> processes = new ArrayList<>();
19+
processes.add(new Process("P1", 0, 5, 10));
20+
processes.add(new Process("P2", 1, 4, 20));
21+
processes.add(new Process("P3", 2, 2, 30));
22+
processes.add(new Process("P4", 4, 1, 40));
23+
24+
List<String> expectedGanttChart = Arrays.asList("P1", "P2", "P3", "P3", "P4", "P2", "P2", "P2", "P1", "P1", "P1", "P1");
25+
26+
// Act
27+
List<String> actualGanttChart = PreemptivePriorityScheduling.preemptivePriorityScheduling(processes);
28+
29+
// Assert
30+
assertEquals(expectedGanttChart, actualGanttChart);
31+
}
32+
}

0 commit comments

Comments
 (0)