从C中的Struct排序,比较和显示

时间:2013-11-14 13:27:34

标签: c comparison

我需要让用户插入进程数,进程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;
}

2 个答案:

答案 0 :(得分:0)

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

这样的东西
if(process[index1].Prio < process[index2].Prio)

答案 1 :(得分:0)

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

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--;
       }
    }
  }
}