0
struct PCB
{
    int PID;
    int burstTime;
    int arrivalTime;
    int priorityScore;
    int startTime;
    int finishTime;
};

struct Queue
{
    int front;
    int rear;
    int length;       // Stores the maximum no. of processes that can be stored processes in the queue
    int size;         // Stores the current no. of processes in the queue
    struct PCB **arr; // Array of pointers storing the pointers to PCB. Storing "struct PCB*" type item in arr
};

void arrangeProcess(struct Queue *readyQ)
{
    if (isEmpty(readyQ))
    {
        printf("\nNo elements in Queue.\n");
        return;
    }

    int i = readyQ->front, temp = readyQ->size;
    int j, tempj;
    struct PCB *key;

    i = (i + 1) % readyQ->length;

    while (i < temp)
    {
        key = readyQ->arr[i];
        j = (i + (readyQ->length) - 1) % readyQ->length; // Getting the previous element of i

        int lastIndex = (readyQ->front + readyQ->length - 1) % readyQ->length;

        // The while loop is executed if (j >= readyQ->front) and AT of arr[j] > AT of key
        while ((j != lastIndex) && ((readyQ->arr[j]->arrivalTime) > (key->arrivalTime))) 
        {
            tempj = (j + 1) % readyQ->length; // Getting the next element of j

            readyQ->arr[tempj] = readyQ->arr[j];

            j = (j + (readyQ->length) - 1) % readyQ->length;
        }
        tempj = (j + 1) % readyQ->length;
        readyQ->arr[tempj] = key;

        i = (i + 1) % readyQ->length;
    }
}

这里的主要目标是根据到达时间readyQ中的PCB进行排序,我尝试使用插入排序来执行此操作,但我找不到合适的条件让插入排序的内部循环为队列运行,直到迭代器i大于等于readyQ的前面元素。如果readyQ已满,即当最后一个元素出现在readyQ中时,我在程序中编写的条件将继续循环,否则它将完美运行。

请建议合适的循环条件,以便即使最后一个元素出现在readyQ中,代码也能完美运行

4

1 回答 1

1

不要使用实际的偏移量。根据 编写循环0..size-1,但实际上比较元素(front + i) % length(front + j) % length

void arrangeProcess(struct Queue *readyQ)
{
    size_t num_eles = readyQ->size;
    if (!num_eles)
        return;

    size_t base_idx = readyQ->front;
    size_t max_eles = readyQ->length;

    for (size_t i=0; i<num_eles-1; ++i) {
        size_t ii = ( base_idx + i ) % max_eles;
        struct PCB *a = readyQ->arr[ii];

        for (size_t j=i+1; j<num_eles; ++j) {
            size_t jj = ( base_idx + j ) % max_eles;
            struct PCB *b = readyQ->arr[jj];

            ...
        }
    }
}

它更简单,更不容易出错。

于 2021-12-12T02:07:49.043 回答