-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorstFitAllocation.java
More file actions
30 lines (25 loc) · 981 Bytes
/
WorstFitAllocation.java
File metadata and controls
30 lines (25 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Arrays;
public class WorstFitAllocation {
public int [] worstFit(int[] memoryBlocks, int[] requests) {
int[] allocation = new int[requests.length];
Arrays.fill(allocation, -1);
for (int i = 0; i < requests.length; i++) {
int req = requests[i];
int worstIndex = -1;
// Find the largest block that can fit the request
for (int j = 0; j < memoryBlocks.length; j++) {
if (memoryBlocks[j] >= req) {
if (worstIndex == -1 || memoryBlocks[j] > memoryBlocks[worstIndex]) {
worstIndex = j;
}
}
}
// Allocate memory if a suitable block is found
if (worstIndex != -1) {
allocation[i] = worstIndex; // Store block index
memoryBlocks[worstIndex] -= req; // Reduce block size
}
}
return allocation;
}
}