-1

我需要让用户插入进程数、进程 ID 和等待时间,然后我必须根据进程优先级进行排序、比较和打印我是 C 新手,我不知道该怎么做 感谢任何帮助 谢谢提前*/

struct Process {
  int Id;
  int Prio;
  int Time;
};

struct Process process[100];


void init() {
  printf("Enter number of processes:\n ");
  scanf("%d",&n);
  while(n<3) {
    printf("Number has to be grater than 2\n");
    scanf("%d",&n);
  }

  for (int x=0; x<n; x++) {
    printf("Process %d ID:\n ", x+1);
    scanf("%d",&process[x].Id);
    printf("Process %d priority:\n ", x+1);
    scanf("%d",&process[x].Prio);
    printf("Process %d time:\n ", x+1);
    scanf("%d",&process[x].Time);
    }
}

void priority() {
  for (int x=0; x<n; x++) {
    printf("%d",process[x].Id);
    printf("        %d",process[x].Prio);
    printf("           %d\n\n",process[x].Time);
  }
}

void line(int dashes) {
  for(int x=1;x<dashes;x++) {
    printf("-");
  }
}

void display() {
  printf("\n");
  printf("                        PROCESS SCHEDULING\n");
  line(90);
  printf("\n");
  printf("ID");
  printf("    PRIORITY");
  printf("    WAITING TIME");
  line(90);
  printf("\n\n");
}
int main() {
  init();
  display();
  priority();
  return 0;
}
4

2 回答 2

0

这是 BubbleSort 的一个实现,一种用于排序的基本算法。这不是你能找到的最好的,但它是最容易理解的之一。参考这里

void SortProcesses()
{
  int right_bound = n - 1; /* Assuming you've declared n as number of processes inputed. */
  Process swap;

  while( right_bound > 0 )
  {
    for( int i = 0; i < right_bound; i++ )
    {
       if( process[i].Prio > process[i + 1].Prio )
       {
         swap.Id = process[i+1].Id;
         swap.Prio = process[i+1].Prio;
         swap.Time = process[i+1].Time;
         process[i+1].Id = process[i].Id;
         // ... idem for Prio and Time;
         process[i].Id = swap.Id;
         // ... idem for Prio and Time
         right_bound--;
       }
    }
  }
}
于 2013-11-14T13:50:52.120 回答
0

对于排序,您可以应用任何排序算法(冒泡排序、插入排序、堆排序......),但在比较相邻元素时,请比较它们的优先级。就像是

if(process[index1].Prio < process[index2].Prio)
于 2013-11-14T13:42:11.643 回答