算法/调度算法/ShortJobFirst(SJF)短作业优先调度算法

问题描述

SJF(Short Job First)短作业优先,又称为SPN(Short Process Next)短进程优先,这是对FCFS(First Come First Service)先来先服务算法的改进,其目的是减少平均周转时间。定义为:对预计执行时间短的作业/进程优先分派处理机,通常后来的短作业不抢先正在执行的作业。

A simple scheduling problem. We are given jobs j1, j2… jn, all with known running time t1, t2… tn, respectively. We have a single processor. What is the best way to schedule these jobs in order to minimize the average completion time. Assume that it is a non-preemptive scheduling: once a job is started, it must run to completion. ( 同算法导论16-2(a) )

The following are some instances:
(j1,j2,j3,j4):(15,8,3,10)


求解过程

算法/调度算法/ShortJobFirst(SJF)短作业优先调度算法_第1张图片

这个问题比一般的SJF算法要简单得多,不赘述直接上代码,完整的SJF解答过程以后会再完善

public class Scheduling {
    private void scheduling(int[] times) {

        int n = times.length;//任务数

        int[] turnoverTime = new int[n];//每个任务的周转时间

        double sumTurnoverTime;//总周转时间

        double aveTurnoverTime;//平均任务周转时间


//        按服务时间由小到大排序
        for (int i = 0; i < n; i++) {
            for (int j = 1; j < n - i; j++) {
                if (times[j - 1] > times[j]) {
                    int temp = times[j];
                    times[j] = times[j - 1];
                    times[j - 1] = temp;
                }
            }
        }

        turnoverTime[0] = times[0];
        sumTurnoverTime = times[0];
        for (int i = 1; i < n; i++) {
            turnoverTime[i] = times[i] + turnoverTime[i - 1];
            sumTurnoverTime += turnoverTime[i];
        }


        System.out.println("调度方案为:");
        for (int time : times) {
            System.out.print(time + " ");
        }
        System.out.println();

        aveTurnoverTime = sumTurnoverTime / n;
        System.out.println("平均最短完成时间为:" + aveTurnoverTime);
    }


    public static void main(String[] args) {
        int[] times = {15, 8, 3, 10};
        new Scheduling().scheduling(times);
    }
}

你可能感兴趣的:(算法导论)