基于这篇博客(280条消息) 快速排序算法C++实现(超详细解析!!!!)_快速排序c++_sunny-ll的博客-CSDN博客
#include <stdio.h>
#pragma comment(linker, "/STACK:1073741824")
const int maxn = 1000001;
int A[maxn];
void swap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
int partition(int arr[], int low, int high)
{
// Insert your code here
int i = low,j=high,t=arr[low];
while(i<j)
{
while(i<j&&arr[j]>t) {
j--;
}
if(i<j) {
swap(arr[j],arr[i]);
i++;
}
while(i<j&&arr[i]<=t) {
i++;
}
if(i<j) {
swap(arr[i],arr[j]);
j--;
}
//这里两个while循环必须先处理j再处理i,也就是必须先从右边开始扫再从左边扫,如果调转顺序就会出错!!也就是不能先while(i<j&&arr[i]<=t)再 while(i<j&&arr[j]>t) 至于原因我猜大概是i<j的临界判断条件会有问题
return i;
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int k = partition(arr, low, high);
// Insert your code here
quickSort(arr,low,k-1);
quickSort(arr,k+1,high);
}
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &A[i]);
quickSort(A,0,n-1); // Correct this line
for (int i = 0; i < n; i++)
printf("%d ", A[i]);
return 0;
}