最差适应算法原理及java代码
时间: 2023-10-19 11:09:24 浏览: 119
最差适应算法(Worst Fit Algorithm)是一种内存分配算法,其原理是在分配内存时,选择剩余空间最大的块进行分配。这种算法的优点是可以避免出现过多的小碎片,但是会导致剩余空间较小的块无法被利用。
以下是最差适应算法的Java代码实现:
```java
public class WorstFit {
public static void main(String[] args) {
int[] blockSize = {100, 500, 200, 300, 600};
int[] processSize = {212, 417, 112, 426};
worstFit(blockSize, processSize);
}
public static void worstFit(int[] blockSize, int[] processSize) {
int[] allocation = new int[processSize.length];
Arrays.fill(allocation, -1);
for (int i = 0; i < processSize.length; i++) {
int worstIndex = -1;
for (int j = 0; j < blockSize.length; j++) {
if (blockSize[j] >= processSize[i]) {
if (worstIndex == -1 || blockSize[j] > blockSize[worstIndex]) {
worstIndex = j;
}
}
}
if (worstIndex != -1) {
allocation[i] = worstIndex;
blockSize[worstIndex] -= processSize[i];
}
}
System.out.println("Process No.\tProcess Size\tBlock no.");
for (int i = 0; i < processSize.length; i++) {
System.out.print(" " + (i+1) + "\t\t" + processSize[i] + "\t\t");
if (allocation[i] != -1) {
System.out.print(allocation[i] + 1);
} else {
System.out.print("Not Allocated");
}
System.out.println();
}
}
}
```
阅读全文