1. 程式人生 > >磁碟排程演算法(FCFS&&SSTF)

磁碟排程演算法(FCFS&&SSTF)

作業系統磁碟排程演算法之FCFS和SSTF篇,我感覺自己寫的好垃圾啊!!!

#include <iostream>
#include <cstdlib>
using namespace std;
void FCFS(int a[],int n)
{
    int sum = 0;
    int i,j,now;
    float avg;
    cout << "請輸入當前的磁軌號:";
    cin >> now;//確定當前磁頭所在位置
    cout << "磁碟排程順序為:" << endl;
    for
(i = 0; i < n; i++)//按訪問順序輸出磁軌號 { cout << a[i] <<" "; } cout << endl; sum += abs(a[0] - now); cout << "從當前位置到第1個磁軌移動的磁軌數為:" << sum << endl; for(i = 0,j = 1; j < n; i++,j++) { sum += abs(a[j] - a[i]);//外圍磁軌與最裡面磁軌的距離 cout
<< "從第" << i+1 << "個磁軌到第" << j+1 << "個磁軌的移動距離為:" << abs(a[j] - a[i]) << endl; } cout << endl; cout << "移動的總磁軌數為:" << sum <<endl; avg = sum * 1.0 / n; cout << "平均尋道長度為:" << avg << endl; } void SSTF(int
a[],int n) { int temp; int now,L,r; int j,i; int k = 1; int sum = 0; float AVG; //氣泡排序法對磁軌號進行排序 for(i = 0; i < n; i++) for(j = i + 1; j < n; j++) { if(a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } cout <<"按遞增順序排好的磁軌:" << endl; for(i = 0; i < n; i++) cout << a[i] << " ";//輸出排好的磁軌順序 cout << endl; cout << "請輸入當前的磁軌號:"; cin >> now;//確定當前磁頭所在位置 cout << "磁碟排程順序為:" << endl; if(now >= a[n-1])//當前磁頭位置大於最外層欲訪問磁軌 { for(i = n-1; i >= 0; i--) cout << a[i] << " " << endl;//則磁碟呼叫從大到小 cout << "從當前位置到第1個磁軌移動的磁軌數為:" << now - a[n-1] << endl; for(i = 0,j = 1; j < n; i++,j++) cout << "從第" << i+1 << "個磁軌到第" << j+1 << "個磁軌的移動距離為:" << abs(a[j] - a[i]) << endl; sum = now - a[0];//(now - a[n-1]) + (a[n-1) - a[n-2]) + .... + (a[1] -a[0]) } else if(now < a[0])//當前磁頭位置小於最外層欲訪問磁軌 { for(i = 0; i < n; i++) cout << a[i] << " " << endl;//則磁碟呼叫從小到大 cout << "從當前位置到第1個磁軌移動的磁軌數為:" << a[0] - now << endl; for(i = 0,j = 1; j < n; i++,j++) cout << "從第" << i+1 << "個磁軌到第" << j+1 << "個磁軌的移動距離為:" << abs(a[j] - a[i]) << endl; sum = a[n-1] - now;//同上面 } else { while(a[k] < now) k++;//確定當前磁軌在已排序的序列中的位置 L = k -1;//在磁頭位置的前一個欲訪問磁軌 r = k;//磁頭欲訪問位置 while((L >= 0) && (r < n)) { if((now - a[L]) <= (a[r] - now))//選擇離磁頭近的磁軌 { cout << a[L] << " "; sum += now - a[L]; now = a[L];//將磁頭位置移到第L個 L--;//L減一,準備好下一個 } else { cout << a[r] << " "; sum += a[r] - now; now = a[r];//將磁頭位置移到第r個 r++;//r增一,準備好下一個 } } if(L = -1)//磁頭位置裡側的磁軌已訪問完 { for(j = r; j < n; j++) cout << a[j] << " "; sum += a[n-1] -a[0]; } if(r == n) { for(j = k - 1; j > -1; j--) cout << a[j] << " "; sum += a[n-1] - a[0]; } } cout << endl; cout << "移動的總磁軌數:" << sum <<endl; AVG = sum * 1.0 / n; cout << "平均尋道長度為:" << AVG << endl; } int main() { int n;//此道的個數 int s;//功能號 int i; cout << "請輸入磁軌個數:" << endl; cin >> n; int *a = new int[n]; for(i = 0;i < n; i++) { cout << "請輸入第" << i+1 << "個磁軌號:"; cin >> a[i]; } cout << endl; while(1) { cout << endl; cout << "1:先來先服務演算法:" << endl; cout << "2:最短尋道時間演算法:" << endl; cout << "0:退出" << endl; cout << endl; cout << "請選擇功能號:"; cin >> s; if(s > 2) { cout << "輸入錯誤!" << endl; } else { switch(s) { case 0:exit(0);break; case 1:FCFS(a,n);break; case 2:SSTF(a,n);break; } } } return 0; }

這裡寫圖片描述
這裡寫圖片描述