In this algorithm, the R/W head looks for the nearest track number to serve the I/O request.
Let’s consider a disk containing 200 tracks(0-199)
, a request queue containing track numbers [82,170,43,140,24,16,190]
, and the current position of read-write head=50
.
The requirement is to find the total number of track movements in cylinders.
7
.82 170 43 140 24 16 190
.50
.# include<stdio.h>#include<stdlib.h>int main(){int ReadyQueue[100],i,n,TotalHeadMoment=0,initial,count=0;// The number of requestsscanf("%d",&n);//Enter the requests sequencefor(i=0;i<n;i++)scanf("%d",&ReadyQueue[i]);//Enter the initial head positionscanf("%d",&initial);while(count!=n){int min=1000,diff,index;for(i=0;i<n;i++){diff=abs(ReadyQueue[i]-initial);if(min>diff){min=diff;index=i;}}TotalHeadMoment=TotalHeadMoment+min;initial=ReadyQueue[index];ReadyQueue[index]=1000;count++;}printf("Total head movement is %d",TotalHeadMoment);}
Enter the input below
Line 5: We declare the variables ReadyQueue[100]
,TotalHeadMoment=0
,initial
, and count=0
.
Lines 6 to12: We ask the user to provide the number of requests
, the sequence of requests
, and the initial head position
as input.
Lines 15 to 20: To find the least head movement required to serve the request, we try to determine the difference between each head request diff=abs(ReadyQueue[i]-initial)
.
Lines 20 to 25: We follow the below steps.
min
with a large value 1000
in the code.min
value with the difference diff
calculated earlier, based on the condition min
> diff
. We check if the min
value is greater than the diff
value or not.min
variable a value of diff
. This is to ensure that the variable min
contains the minimum value.Lines 26 to 32: We add up the total head movements after each request served. Finally, we print the total number of head movements.