【发布时间】:2020-01-08 20:04:55
【问题描述】:
我正在尝试使用快速排序对数组“选项卡”中的值进行排序,但它不起作用。主函数只是为每个选项卡设置名称和薪水[n]
typedef struct employee Employee;
struct employee{
char name[81];
float salary;
};
Employee *tab[10];
void sort(Employee **tab, int begin, int end){
int p = tab[(begin + end) / 2] , i = end, j = begin;
/*p is the pivot*/
do{
while(tab[i]->salary < p && i < end) i++;
while(tab[j]->salary > p && j > begin) j--;
if(i <= j){
int tmp = tab[i]->salary;
tab[i]->salary = tab[j]->salary;
tab[j]->salary = tmp;
i++; j--;
}
}while(i <= j);
if(begin < j) sort(tab, begin, j);
if(end > i) sort(tab, i, end);
}
【问题讨论】:
-
您的支点
p是Employee*,而不是int -
它在什么方面不起作用?它在什么大小的数组上失败(0、1、2、3、4,更多元素)?它失败的样本数据是什么?
Employee结构是什么样的?为什么你只交换薪水而不是整个员工记录?名字在前的人薪水最低,名字在后的人薪水最高?反之亦然? -
我可能错了,但不应该是 float p = tab[(begin + end) / 2] ->salary 吗?在接下来的 2 个 while 循环中,您将浮点数 (tab[i]->salary 和 tab[j]->salary) 与 int (p) 进行比较,而 int (p)(正如 mangusta 指出的那样)又等同于结构元素指针,你应该交换第i和第j个结构元素,而不仅仅是薪水。
-
你得到了我的支持@JL2210,但我不确定从长远来看我们会赢。大约 5 年后的某个时候,我可能会停止使用该版本(这是我复制粘贴的预设序列,而不是我在需要时从头开始输入的内容)。
-
@JL2210:我将它们保存在 GitHub 上我的 SOQ 存储库中 - 在
src/scripts目录中。这个是sscce。我主要在 Mac 上工作,所以sscce | sed 5q | pbcopy在粘贴缓冲区中为我提供了上面引用的文本,然后 command-V (⌘-V) 将其放入评论中。第 6 行以上的其他链接是:另见 How to s the Smart Way 和 Writing the perfect question