class Solution {
private:
void merge(vector<int>& nums, int l, int mid, int r){
vector<int> nums_temp(r-l+1, 0);
int l1 = l, l2 = mid+1;
int k = 0;
while(l1 <= mid && l2 <= r){
if(nums[l1] <= nums[l2]){
nums_temp[k++] = nums[l1++];
}else{
nums_temp[k++] = nums[l2++];
}
}
while(l1 <= mid){
nums_temp[k++] = nums[l1++];
}
while(l2 <= r){
nums_temp[k++] = nums[l2++];
}
for(int i = 0; i < nums_temp.size(); ++i){
nums[l+i] = nums_temp[i];
}
return;
}
void mergeSort(vector<int>& nums, int l, int r){
if(l >= r) return;
int mid = (l+r) >> 1;
mergeSort(nums, l, mid);
mergeSort(nums, mid+1, r);
merge(nums, l, mid, r);
}
int partition(vector<int>& nums, int l, int r){
int pivot = nums[l];
int i, j;
i = l, j = r;
while(i < j){
while(nums[j] >= pivot && i < j)
j--;
while(nums[i] <= pivot && i < j)
i++;
//两个while循环结束后,能得到左边第一个大于pivot的以及右边第一个小于pivot的,将他们交换
swap(nums[i], nums[j]);
}
//退出这个大的while循环后,i == j且nums[i] == nums[j] < pivot;
swap(nums[l], nums[i]);
return i;
}
int randomized_partition(vector<int>& nums, int l, int r) {
int i = rand() % (r - l + 1) + l; // 随机选一个作为我们的主元
swap(nums[l], nums[i]);
return partition(nums, l, r);
}
void quickSort(vector<int>& nums, int l, int r){
if(l >= r) return;
int pos = randomized_partition(nums, l, r);
quickSort(nums, l, pos-1);
quickSort(nums, pos+1, r);
return;
}
public:
vector<int> sortArray(vector<int>& nums) {
if(nums.size() <= 1) return nums;
//归并排序
// mergeSort(nums, 0, nums.size()-1);
//快速排序
quickSort(nums, 0, nums.size()-1);
return nums;
}
};
归并排序和快速排序算法
于 2022-03-07 11:09:49 首次发布