C++記憶體管理中最佳適配演算法程式
給定兩個包含塊大小和程序大小的陣列;任務是根據記憶體管理中的最佳適配演算法列印結果。
什麼是最佳適配演算法?
最佳適配是一種記憶體管理演算法;它處理分配滿足請求程序需求的最小空閒分割槽。在這種演算法中,我們查詢整個記憶體塊並檢查最適合程序的最小塊,然後查詢可用於滿足適當程序的緊鄰塊。
因此,我們將獲取塊大小和程序大小,並返回程序的輸出以及要分配給程序的塊。

示例
Input: bsize[] = {100, 500, 200, 300, 400}
psize[] = {112, 518, 110, 526}
Output:
Process No. Process Size Block no.
1 112 3
2 518 Not Allocated
3 110 4
4 526 Not Allocated將使用的方法來解決上述問題 -
- 獲取程序和塊大小的輸入。
- 最初將所有記憶體塊設定為空閒。
- 獲取每個程序並找到可以分配給塊的最小塊大小,這意味著大於程序大小的整個塊的最小值。
- 如果找到,則將其分配給當前程序,否則放棄該程序並檢查後續程序。
演算法
Start
Step 1-> In function void bestfit(int bsize[], int m, int psize[], int n)
Declare int alloc[n]
Call function memset(alloc, -1, sizeof(alloc))
Loop For i=0 and i<n and i++
Declare and Initialize bestIdx = -1
Loop For j=0 and j<m and j++
If bsize[j] >= psize[i] then,
If bestIdx == -1 then,
Set bestIdx = j
Else If bsize[bestIdx] > bsize[j] then,
Set bestIdx = j
If bestIdx != -1 then,
Set alloc[i] = bestIdx
Set bsize[bestIdx] -= psize[i]
Loop For i = 0 and i < n and i++
Print i+1, psize[i]
If alloc[i] != -1
Print alloc[i] + 1
Else
Print "Not Allocated"
Print newline
Step 2->In function int main()
Declare and initialize bsize[] = {100, 500, 200, 300, 400}
Declare and initialize psize[] = {112, 518, 110, 526}
Set m = sizeof(bsize)/sizeof(bsize[0])
Set n = sizeof(psize)/sizeof(psize[0])
Call function bestfit(bsize, m, psize, n)
Stop示例
#include <iostream>
#include <memory>
using namespace std;
// To allocate the memory to blocks as per Best fit
// algorithm
void bestfit(int bsize[], int m, int psize[], int n) {
// To store block id of the block allocated to a
// process
int alloc[n];
// Initially no block is assigned to any process
memset(alloc, -1, sizeof(alloc));
// pick each process and find suitable blocks
// according to its size ad assign to it
for (int i=0; i<n; i++) {
// Find the best fit block for current process
int bestIdx = -1;
for (int j=0; j<m; j++) {
if (bsize[j] >= psize[i]) {
if (bestIdx == -1)
bestIdx = j;
else if (bsize[bestIdx] > bsize[j])
bestIdx = j;
}
}
// If we could find a block for current process
if (bestIdx != -1) {
// allocate block j to p[i] process
alloc[i] = bestIdx;
// Reduce available memory in this block.
bsize[bestIdx] -= psize[i];
}
}
cout << "\nProcess No.\tProcess Size\tBlock no.\n";
for (int i = 0; i < n; i++) {
cout << " " << i+1 << "\t\t\t\t" << psize[i] << "\t\t\t\t";
if (alloc[i] != -1)
cout << alloc[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}
// Driver code
int main() {
int bsize[] = {100, 500, 200, 300, 400};
int psize[] = {112, 518, 110, 526};
int m = sizeof(bsize)/sizeof(bsize[0]);
int n = sizeof(psize)/sizeof(psize[0]);
bestfit(bsize, m, psize, n);
return 0 ;
}輸出
Process No. Process Size Block no. 1 112 3 2 518 Not Allocated 3 110 4 4 526 Not Allocated
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP