百度2016实习笔试:短作业优先调度算法(SJF)的平均等待时间---java版本


假设有n项作业位于就绪队列中,这些作业的提交时间用数组requestTimes按照提交时间的先后顺序存储,对应的作业服务时间(持续时间)用数组durations存储。采用SJF算法,计算n项作业的平均等待时间。

public class code {

public static int[] getMinIndex(int[] arr) {
int[] res = {Integer.MAX_VALUE,0};
for (int i = 0,len = arr.length; i < len; i++) {
if(res[0] > arr[i]) {
res[0] = arr[i];
res[1] = i;
}
}
arr[res[1]] = Integer.MAX_VALUE; 
return res;
}

public static float minWaitingTime(int[] req, int[] dur) {
int res = 0,cur = dur[0];
dur[0] = Integer.MAX_VALUE;
for(int i=1,len = req.length;i<len;i++) {
int[] nextTask =  getMinIndex(dur);
int curStart = req[nextTask[1]];
if( cur > curStart ) {
res +=  cur - curStart;
cur += nextTask[0];
}
else {
cur += curStart+nextTask[i];
}
}
return res;
}

public static void main(String[] args) {
int[] a = {0, 2, 4, 5};
int[] b = {7, 14, 21, 4};
System.out.println(minWaitingTime(a,b));
}
}

你可能感兴趣的:(java,算法,SJF)