void quicksort(Student *students, int left, int right) { Student record = students[low]; while (low < high) { while (low<high &&students[high].score<=record.score) { --high; } students[low]=students[high]; while (low<high&&students[low].score>=record.score) { ++low; } students[high]=students[low]; } students[low]=record; quicksort(students,low,low-1); quicksort(students,low+1,high); }改进这段快速排序代码
时间: 2024-02-05 10:02:38 浏览: 56
快速排序——quicksort
这段快速排序代码有几个问题:
1. `low` 和 `high` 没有被定义,应该是 `left` 和 `right`;
2. 没有对边界情况进行处理,需要在递归出口处加上 `if (left >= right) return;`;
3. 在交换元素时,应该使用临时变量,而不是直接赋值。
改进后的代码如下:
```
void quicksort(Student *students, int left, int right) {
if (left >= right) return;
int low = left, high = right;
Student record = students[low];
while (low < high) {
while (low < high && students[high].score <= record.score) {
--high;
}
students[low] = students[high];
while (low < high && students[low].score >= record.score) {
++low;
}
students[high] = students[low];
}
students[low] = record;
quicksort(students, left, low - 1);
quicksort(students, low + 1, right);
}
```
改进后的代码处理了边界情况,并使用临时变量进行了交换,可以更可靠地排序。
阅读全文