LeetCode 912. 排序数组
双边循环写法
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
return quickSort(nums);
}
vector<int> quickSort(vector<int>& nums){
int n = nums.size();
quickCore(nums,0,n - 1);
return nums;
}
void quickCore(vector<int>& nums,int left,int right){
if(left >= right){
return;
}
int base = nums[left];
int l = left;
int r = right;
while(l < r){
while(l < r && nums[r] >= base)--r;
if(l < r)
nums[l++] = nums[r];
while(l < r && nums[l] <= base)++l;
if(l < r)
nums[r--] = nums[l];
}
nums[l] = base;
quickCore(nums,left,l-1);
quickCore(nums,l+1,right);
return;
}
};
单边循环快排
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
return quickSort(nums);
}
vector<int> quickSort(vector<int>& nums){
int n = nums.size();
quickCore(nums,0,n - 1);
return nums;
}
void quickCore(vector<int>& nums,int left,int right){
if(left >= right){
return;
}
int base = nums[left];
int m = left;
for(int i = left + 1; i <= right; i++){
if(nums[i] < base){
m++;
swap(nums[m],nums[i]);
}
}
swap(nums[m],nums[left]);
quickCore(nums,left,m-1);
quickCore(nums,m+1,right);
return;
}
};