您的位置:首页 > 理论基础 > 数据结构算法

华为2012机试第三题

2015-07-30 22:00 525 查看
3、操作系统任务调度问题。操作系统任务分为系统任务和用户任务两种。其中,系统任务的优先级 < 50,用户任务的优先级 >= 50且 <= 255。优先级大于255的为非法任务,应予以剔除。现有一任务队列task[],长度为n,task中的元素值表示任务的优先级,数值越小,优先级越高。函数scheduler实现如下功能,将task[]
中的任务按照系统任务、用户任务依次存放到 system_task[] 数组和 user_task[] 数组中(数组中元素的值是任务在task[] 数组中的下标),并且优先级高的任务排在前面,优先级相同的任务按照入队顺序排列(即先入队的任务排在前面),数组元素为-1表示结束。

      例如:task[] = {0, 30, 155, 1, 80, 300, 170, 40, 99}    system_task[] = {0, 3, 1, 7, -1}    user_task[] = {4, 8, 2, 6, -1}

      函数接口    void scheduler(int task[],
int n, int system_task[], int user_task[])

逻辑弄清楚,代码提交給面试官看之前先运行几个测试用例检查一下

<span style="font-size:14px;">#include<stdio.h>

const int MAXN = 100;

void scheduler(int task[], int n, int system_task[], int user_task[])
{
if(task == NULL || n < 1 || system_task == NULL || user_task == NULL)
{
return;
}

int usefulNumbers = 0;
for(int i = 0; i < n; ++i)
{
if(task[i] <= 255)
usefulNumbers++;
}

//printf("%d\n", usefulNumbers);
int systemIndex = 0;
int userIndex = 0;
int small = 0x7FFFFFFF;
int smallIndex = 0;
for(int i = 0; i < usefulNumbers; ++i)
{
small = 0X7FFFFFFF;//注意这条语句的位置,在下一个循环里就不对了
for(int j = 0; j < n; ++j)
{
if(task[j] < small)
{
small = task[j];
smallIndex = j;
}
}
if(small < 50) //这个判断条件也应该放在外面,逻辑弄清楚了
{
system_task[systemIndex++] = smallIndex;
task[smallIndex] = 256;
}else if(small >= 50 && small <= 255)
{
user_task[userIndex++] = smallIndex;
task[smallIndex] = 256;
}

}
system_task[systemIndex] = -1;
user_task[userIndex] = -1;

for(int i = 0; i < systemIndex; ++i)
{
printf("%d ", system_task[i]);
}
printf("%d\n", system_task[systemIndex]);

for(int i = 0; i < userIndex; ++i)
{
printf("%d ", user_task[i]);
}
printf("%d\n", user_task[userIndex]);
}
int main()
{
int task[] = {0, 30, 155, 1, 80, 300, 170, 40, 99};
int system_task[MAXN], user_task[MAXN];

scheduler(task, 9, system_task, user_task);

return 0;
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息