1.霍尔法
#include <iostream>
using namespace std;
int partition(int *arr,int left,int right){
int pivotIndex=left;
while(left<right){
while(left<right && arr[right]>=arr[pivotIndex]){
right--;
}
while(left<right && arr[left]<=arr[pivotIndex]){
left++;
}
swap(arr[left],arr[right]);
}
swap(arr[left],arr[pivotIndex]);
return left;
}
void quicksort(int *arr,int left,int right){
if(left<right){
int pivotIndex=partition(arr,left,right);
quicksort(arr,left,pivotIndex-1);
quicksort(arr,pivotIndex+1,right);
}
}
int main(){
int n;
cin>>n;
int arr[100005];
for(int i=0;i<n;i++){
cin>>arr[i];
}
quicksort(arr,0,n-1);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
2. 竞赛用
题目链接:https://www.luogu.com.cn/problem/P1177
#include <iostream>
using namespace std;
void quicksort(int *arr,int left,int right){
if(left>=right) return;
int l=left-1,r=right+1,pivot=arr[(left+right)/2];
while(l<r){
do l++;while(arr[l]<pivot);
do r--;while(arr[r]>pivot);
if(l<r) swap(arr[l],arr[r]);
}
quicksort(arr,left,r);
quicksort(arr,r+1,right);
}
int main(){
int n;
cin>>n;
int arr[100005];
for(int i=0;i<n;i++){
cin>>arr[i];
}
quicksort(arr,0,n-1);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}