天天看點

OS的最短尋道時間優先算法SSTF

該算法要求通路的磁道與目前磁頭所在的距離你最近,使尋道時間最短

例如給資料90,58,55,39,38,18,150,160,184 平均尋道長度為27.5

原理見湯子瀛的《作業系統》第四版 p233頁

首要的是分析如何才能找到第一個最接近的磁道号,先把資料存數組,遞增排序,動态找到最接近值,然後依次左右分别的引用2指針比大小,求和

#include <iostream>
#include <math.h>
#include <algorithm>
using namespace std;
//排序條件
bool cp(int a, int b)
{
	return a < b;
}
int main()
{
	int* p = new int[9];
	int cnt = 0;
	while (cnt < 9)
	{
		std::cin >> p[cnt++];
	}
	sort(p, p + 9, cp);
	//first find min position
	int begin_position, first_position = p[0], first = 0;
	//輸入開始要磁道号位置
	cin >> begin_position;
	//假設第一個0位置是最接近值
	int min_position = abs(begin_position - p[0]);
	for (int i = 1; i < 9; ++i)
	{
	//動态的比較前者與後者的大小
		if (abs(begin_position - p[i]) < min_position)
		{
		//目前下标位置
			first = i;
			min_position = abs(begin_position - p[i - 1]);
		}
	}
	//	cout<<first_position;
	int sum_position = 0, average_cnt = 0;
	//雙指針 
	int left, right, current_mid;
	left = right = current_mid = first;
	while (true)
	{
	//先把第一個尋道路徑值求出來累加
		sum_position += abs(begin_position - p[current_mid]);
		average_cnt++;
		//重定位
		begin_position = p[current_mid];
		//臨界判斷
		if (current_mid == 0 || current_mid == 8)break;
		//當左邊的大于右邊的差,則定位到左邊
		if (abs(p[current_mid] - p[left - 1]) < abs(p[current_mid] - p[right + 1]))
		{
			current_mid = --left;
		}
		else
		{
			current_mid = ++right;
		}
	}//當指着移動到最左邊時候,可能存在右邊沒有處理完資料
	if (left == 0 )
	{
		begin_position = p[left];
		for (int i = right+1; i < 9; ++i)
		{
			sum_position += abs(begin_position - p[i]);
			begin_position = p[i];
			average_cnt++;
		}
	}
	//同理
	if (right == 8)
	{
		begin_position = p[right];
		for (int i = left - 1; i >= 0; i--)
		{
			sum_position += abs(begin_position - p[i]);
			begin_position = p[i];
			average_cnt++;
		}
	}
	std::cout <<static_cast<double>(sum_position) / average_cnt;
	return 0;
}
           
c++

繼續閱讀