按开始时间对完成的请求进行排序

时间:2019-07-08 11:33:41

标签: algorithm performance sorting data-structures

给出ID为未知时间的请求: 1. StartRequest(int id) 2. EndRequest(int id)

我需要返回完成请求的ID,以及它花费的总时间(endTime-startTime)(按开始时间排序)。

请注意,如果之前的请求尚未完成,即使当前请求已完成,也不返回当前请求。

我尝试过幼稚的方式: 在开始请求时,我添加到列表中,在结束请求时,我检查从列表开始到第一个未完成的请求是否存在,然后将它们返回。

有没有更有效的方法?是在EndRequest上返回结果的最佳方法吗?

1 个答案:

答案 0 :(得分:1)

使用常用/常用语言使用以下proc:

public class StartEndRequest {
private static void swap(int [] starts, int [] ends, int i, int j) {
    int temp = starts[i];
    int temp1 = ends[i];

    starts[i] = starts[j];
    ends[i] = ends[j];

    starts[j] = temp;
    ends[j] = temp1;
}
// selection sort ..
private static void sortByProcessTime(int [] starts, int [] ends) {
    for(int i=0; i<starts.length-1; i++) {
        int min = i;
        for(int j=i+1; j<starts.length; j++) {
            // swap according to execution time..
            if((ends[j] - starts[j]) > (ends[i] - starts[i]))
                min = j;
        }

        swap(starts, ends, i, min);
    }
}
private static ArrayList<ArrayList<Integer>> getFinishedProcess(int [] prevProcess, int [] starts, int [] ends){
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();

    for(int i=0; i<prevProcess.length; i++) {
        // add the first operation, it has no prev. operation..
        if(i == 0) {
            ArrayList<Integer> temp = new ArrayList<>();
            temp.add(starts[i]);
            temp.add(ends[i]);

            list.add(temp);
        }
        if(prevProcess[i] != -1) {
            ArrayList<Integer> temp = new ArrayList<>();
            temp.add(starts[i]);
            temp.add(ends[i]);

            list.add(temp);
        }
    }
    return list;
}
private static void blockUnfinishedProcess(int [] preProcesses, int [] starts, int [] ends) {
    for(int i=1; i<preProcesses.length; i++) {
        if(ends[i] == -1) {
            preProcesses[i] = -1;
        }
    }
}
public static void main(String[] args) {
    // use an auxiliary space to point prev. operations..
    int [] prevProcess = {-1, 0, 0, 0, 0, 0};
    int [] startReq = {2, 3, 1, 4, 6, 5};
    // i am using -1 to indicate unfinished jobs..
    int [] endReq = {7, 4, 3, -1, 8, -1};

    // sort according to execution time..
    sortByProcessTime(startReq, endReq);

    // block those operation whose prev was not finished ..
    blockUnfinishedProcess(prevProcess, startReq, endReq);

    //
    for(int i=0; i<startReq.length; i++) {
        System.out.println(startReq[i]+" -- "+endReq[i]);
    }

    // add only those operation, whose prev also executed successfully.. 
    System.out.println(getFinishedProcess(prevProcess, startReq, endReq));
}

}