【问题标题】:In a circular queue how to check if the iterator is greater than and equal to the front element of the queue在循环队列中如何检查迭代器是否大于等于队列的前面元素
【发布时间】:2022-01-16 01:58:10
【问题描述】:
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

中存在最后一个元素的情况下也能完美运行

【问题讨论】:

    标签: c pointers queue insertion-sort circular-queue


    【解决方案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-11-11
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多