错误代码:
void quicksort(int l,int r){
if(l>=r)return;
int t = rand() % (r - l + 1) + l;
swap(Nums[t],Nums[r]);
int i=l+1,j=r;
int key=Nums[l];
while(i<j){
while(i<j&&Nums[j]>=key)j--;
while(i<j&&Nums[i]<=key)i++;
if(i<j)swap(Nums[i],Nums[j]);
}
if(Nums[l]>=Nums[j])swap(Nums[l],Nums[j]);
quicksort(l,j-1);
quicksort(j+1,r);
}
正确代码:
void quicksort(int l,int r){
if(l>=r)return;
int t = rand() % (r - l + 1) + l;
swap(Nums[t],Nums[r]);
int pivot = Nums[r];
int i = l - 1;
for (int j = l; j <= r - 1; ++j) {
if (Nums[j] <= pivot) {
i = i + 1;
swap(Nums[i], Nums[j]);
}
}
swap(Nums[i + 1], Nums[r]);
quicksort(l,i);
quicksort(i+2,r);
}
还有一种:
int partition( int low, int high)
{
int key = Nums[low];
while(low<high)
{
while(low<high && Nums[high] >= key) --high;
Nums[low] = Nums[high];
while(low<high && Nums[low] <= key) ++low;
Nums[high] = Nums[low];
}
Nums[low] = key;
return low;
麻了