Implementing SJF in C++

Here is C++ implementation of Shortest Job First (SJF) algorithm.

#include<iostream.h>

#include<conio.h>

struct process

{

  int no;

  int at;

  int et;

  int wt;

  int tt;

};

void main()

{

  clrscr();

  process p[4];

  int i, j;

  for (i = 0; i < 4; i++)

  {

    cout << "\n Enter arrival time of P" << i + 1 << ":";

    cin >> p[i].at;

    cout << "\n Enter execution time of P" << i + 1 << ":";

    cin >> p[i].et;

    p[i].no = i;

  }

  cout << "\n PNO\tAT\tET";

  for (i = 0; i < 4; i++)

  {

    cout << "\n P" << p[i].no + 1 << "\t" << p[i].at << "\t" << p[i].et;

  }

  //sorting

  process temp;

  for (i = 0; i < 4; i++)

  {

    for (j = i + 1; j < 4; j++)

    {

      if (p[i].et > p[j].et)

      {

        temp = p[i];

        p[i] = p[j];

        p[j] = temp;

      }

    }

  }

  p[0].wt = 0;

  p[0].tt = p[0].et;

  int tte = p[0].et;

  for (i = 1; i < 4; i++)

  {

    p[i].wt = p[i - 1].wt + p[i - 1].et - (p[i].at - p[i - 1].at);

    p[i].tt = p[i].wt + p[i].et;

    tte = tte + p[i].et;

  }

  cout << " \n Result";

  cout << "\n PNO\tAT\tWT\tET\tTT";

  for (i = 0; i < 4; i++)

  {

    cout << "\n P" << p[i].no + 1 << "\t" << p[i].at << "\t" << p[i].wt << "\t" << p[i].et << "\t" << p[i].tt;

  }

  cout << "\n Total time:" << tte;

  int twt = 0, tat = 0;

  for (i = 0; i < 4; i++)

  {

    twt += p[i].wt;

    tat += p[i].tt;

  }

  float awt = (float) twt / 4;

  cout << "\n Average Waiting time:" << awt;

  float atat = (float) tat / 4;

  cout << "\n Average Turnaround Time:" << atat;

  getch();

}

/* Output





 Enter arrival time of P1:0



 Enter execution time of P1:5



 Enter arrival time of P2:0



 Enter execution time of P2:3



 Enter arrival time of P3:0



 Enter execution time of P3:8



 Enter arrival time of P4:0



 Enter execution time of P4:4



 PNO    AT      ET

 P1     0       5

 P2     0       3

 P3     0       8

 P4     0       4

 Result

 PNO    AT      WT      ET      TT

 P2     0       0       3       3

 P4     0       3       4       7

 P1     0       7       5       12

 P3     0       12      8       20

 Total time:20

 Average Waiting time:5.5

 Average Turnaround Time:10.5



 */

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.