快速排序:为什么第一层while循环里还要判断low<high;第二层while是不是应该加 { }让交换的过程在里面?

int Partition(Sqlist &L,int low,int high) { // 交换顺序表L中子表L.r[low..high]的记录,使枢轴记录到位, 并返回其所在位置,此时在它之前(后)的记录均不大(小)于它 pivotkey=L.r[low].key; //用子表的第一个记录作枢轴记录 while(low&lt;high) { // 从表的两端交替地向中间扫描 while(low&lt;high && L.r[high].key&gt;=pivotkey) --high; L.r[low]交换L.r[high]; while(low&lt;high && L.r[low].key&lt;=pivotkey) ++low; t=L.r[low]交换L.r[high]; } return low; //返回枢轴所在位置 } //Partitionx好吧,我知道了
2026年09月26日 06:03
有2个网友回答
网友(1):

因为在内层的while循环时,higt或者low的值在不停的发生变化,在内层的while内可能出现low>=high的情况。

网友(2):

#include

int count=0; //全局变量 记录进行了多少躺快速排序

void print(int a[],int n){
for(int i=0;i printf("%d ",a[i]);
}
printf("\n");
}

int partition (int a[],int low,int high){
count++;
int lengh = 5; //记录排序数组的长度
printf("第%d次快速遍历前 \n",count);
print(a,lengh);
int temp = a[low];
while(low < high){
while(a[low] <= a[high]) high--;
a[low] = a[high];
while(a[low] <= a[high]) low++;
a[high] = a[low];
}
a[low] = temp;
printf("第%d次快速遍历后 \n",count);
print(a,lengh);

return low;
}

int sort(int a[],int low,int high){
if(low < high){
int pivot = partition(a,low,high);
printf("pivot=%d \n\n ",pivot);
sort(a,low,pivot-1);
sort(a,pivot+1,high);
}
}

int main(){
/*
int a[10]={3,1,2,4,5,6,9,7,10,8};
print(a,10);
sort(a,0,9);
print(a,10);
*/
int a[5]={3,1,2,5,4};
sort(a,0,4);
printf("\n排序结束后\n");
print(a,5);
}
测试一下代码就能看出问题了