java编程实现SJF调度算法
时间: 2024-03-26 19:42:10 浏览: 54
下面是 Java 代码实现 SJF 调度算法的示例:
```java
import java.util.*;
public class SJFScheduling {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of processes: ");
int n = sc.nextInt();
int[] burstTime = new int[n];
int[] waitingTime = new int[n];
int[] turnAroundTime = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter the burst time for process " + (i + 1) + ": ");
burstTime[i] = sc.nextInt();
}
// Sort the burst times in ascending order using selection sort algorithm
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (burstTime[j] < burstTime[minIndex]) {
minIndex = j;
}
}
int temp = burstTime[minIndex];
burstTime[minIndex] = burstTime[i];
burstTime[i] = temp;
}
// Calculate waiting time and turn around time
waitingTime[0] = 0;
turnAroundTime[0] = burstTime[0];
for (int i = 1; i < n; i++) {
waitingTime[i] = waitingTime[i - 1] + burstTime[i - 1];
turnAroundTime[i] = turnAroundTime[i - 1] + burstTime[i];
}
// Calculate average waiting time and turn around time
double avgWaitingTime = 0;
double avgTurnAroundTime = 0;
for (int i = 0; i < n; i++) {
avgWaitingTime += waitingTime[i];
avgTurnAroundTime += turnAroundTime[i];
}
avgWaitingTime /= n;
avgTurnAroundTime /= n;
System.out.println("Process\tBurst Time\tWaiting Time\tTurn Around Time");
for (int i = 0; i < n; i++) {
System.out.println((i + 1) + "\t\t" + burstTime[i] + "\t\t" + waitingTime[i] + "\t\t" + turnAroundTime[i]);
}
System.out.println("Average Waiting Time: " + avgWaitingTime);
System.out.println("Average Turn Around Time: " + avgTurnAroundTime);
}
}
```
在上面的示例中,我们使用选择排序算法将进程的爆裂时间按升序排序。然后,我们计算等待时间和周转时间,并计算它们的平均值。最后,我们将结果打印到控制台上。
阅读全文