/**/ SSTF Algorithm Program in C - Dextutor

SSTF Algorithm Program in C

Before implementing SSTF Algorithm Program in C, let us understand the working of SSTF algorithm. SSTF selects the request with the least seek time from the current head position. SSTF chooses the pending request closest to the current head position.

e.g. for the same question (as in FCFS), the order of request serviced using SSTF will be:
53 -> 65 -> 67 -> 37 -> 14 -> 98 -> 122 -> 124 -> 183
Thus, the total head movement is |65-53|+|67-65|+|37-67|+|14-37|+|98-14|+|122-98|+|124-122|+|183-124| = 12+2+30+23+84+24+2+59 = 236

Variable Description

req[] – array for taking the request, index[] – array for store the distance of each request from current position, a[] – array to store the final sequence in which requests should be fulfilled, min – to find the nearest request from the index array, mini – stores the index of nearest request, mov – to calculate total head movement, cp1 – to save the initial value of current position

SSTF Algorithm Program in C

#include<math.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
    int i,n,k,req[50],mov=0,cp,index[50],min,a[50],j=0,mini,cp1;
    printf("enter the current position\n");
    scanf("%d",&cp);
    printf("enter the number of requests\n");
    scanf("%d",&n);
    cp1=cp;
    printf("enter the request order\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&req[i]);
    }
    for(k=0;k<n;k++)
    {
    for(i=0;i<n;i++)
    {
        index[i]=abs(cp-req[i]); // calculate distance of each request from current position
    }
    // to find the nearest request
    min=index[0];
    mini=0;
    for(i=1;i<n;i++)
    {
        if(min>index[i])
        {
            min=index[i];
            mini=i;
        }
    }
    a[j]=req[mini];
    j++;
    cp=req[mini]; // change the current position value to next request
    req[mini]=999;
    } // the request that is processed its value is changed so that it is not processed again
    printf("Sequence is : ");
    printf("%d",cp1);
    mov=mov+abs(cp1-a[0]);    // head movement
    printf(" -> %d",a[0]);
    for(i=1;i<n;i++)
    {
        mov=mov+abs(a[i]-a[i-1]); ///head movement
        printf(" -> %d",a[i]);
    }
    printf("\n");
    printf("total head movement = %d\n",mov);
}

Output

Relevant Programs

FCFS Algorithm Program in C
LOOK Algorithm Program in C
SCAN Algorithm Program in C