#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
}
int main()
{
int num[11];
srand(time(0));
for(int i=1;i<=10;i++)
num[i]=rand()%100+1;
for(int i=1;i<=5;i++)
cout<<" "<<num[i];
int low=1,high=5;
num[0]=num[1];
//问什么不能用low!=high做判断条件
while(low!=high)
{
while(low!=high&&num[high]>=num[0])
high--;
num[low]=num[high];
if(low==high)
while(low!=high&&num[low]<=num[0])
low++;
num[high]=num[low];
}
num[low]=num[0];
cout<<endl<<num[0]<<endl;
for(int i=1;i<=10;i++)
cout<<" "<<num[i];
return 0;
}
帮你修改了一下,封装成了
partition
函数,顺手补全了整个快排算法╰( ̄▽ ̄)╭先回答你的问题,当然是可以用
low != high
这样的判断,但是不推荐,如果一开始传入的参数比如(10, 1)
,虽然满足条件,但明显会死循环,最好写成low<=high
这样语义性很强的表达式代码出问题的地方我标了出来,你想想嘛:
while
要求low!=high
while
内部要求low==high
low
得不到更新,low
永远不可能与high
相等,这就造成了死循环