# 快速排序 C/C++

0

```#include<bits/stdc++.h>

using namespace std;

int number[100005];

void quicksort(int left, int right)
{
if(left >= right)
return;

int i,j,key;
i = left;
j = right;
key = number[left];

while(i != j)
{
while(number[j] >= key && i < j)
j--;

while(number[i] <= key && i < j)
i++;

if(i < j)
swap(number[i], number[j]);

}

number[left] = number[i];
quicksort(left, i-1);
quicksort(i+1, right);

}

int main()
{
int n;

scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d",&number[i]);

quicksort(1, n);
for(int i = 1; i <= n; i++)
printf("%d ",number[i]);
return 0;

}```

```#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#include <bits/stdc++.h>

using namespace std;

void quick_sort(int nums[],int low,int high)
{
if(low>=high)
{
return;
}

int l=low;
int r=high;
int tmp=nums[l];
while(l<r)
{
while(nums[r]>tmp&&l<r)
r--;

while(nums[l]<=tmp&&l<r)
l++;

if(l<r)
swap(nums[l],nums[r]);

}

swap(nums[low],nums[r]);
quick_sort(nums,low,l-1);
quick_sort(nums,l+1,high);

}

int main()
{
int n,a[100005];
cin>>n;
for(int i=0;i<n;++i)
scanf("%d",a+i);

random_shuffle(a,a+n);//随机乱序
quick_sort(a,0,n-1);

for(int i=0;i<n;++i)
printf("%d ",a[i]);

return 0;
}```

goalltheway | 初学一级 | 园豆：133

0

Conan-jine | 小虾三级 |园豆：1176 | 2020-08-10 19:40

goalltheway | 园豆：133 (初学一级) | 2020-08-10 19:55

@goalltheway: 原理如同下面这篇文章

Conan-jine | 园豆：1176 (小虾三级) | 2020-08-10 19:59

@Conan-jine: 明白了！谢谢！

goalltheway | 园豆：133 (初学一级) | 2020-08-10 20:07

0

while()内部条件搞错了，不一定是i==j的时候跳出循环，有可能是在i>=j的时候跳出循环，这边建议用do while()循环来写quick_sort板子，简洁且易懂

Drophair | 园豆：220 (菜鸟二级) | 2020-08-14 14:02

您需要登录以后才能回答，未注册用户请先注册