LeetCode:
快速排序
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
quickSort(nums, 0, nums.size() - 1);
return nums;
}
void quickSort(vector<int> &nums, int left, int right) {
if (left >= right) { // 边界
return;
}
int i = rand() % (right - left + 1) + left;
swap(nums[left], nums[i]);
int mid = partition(nums, left, right); // 前序遍历
quickSort(nums, left, mid - 1);
quickSort(nums, mid + 1, right);
}
int partition(vector<int>& nums, int l, int r)
{
int pivot = nums[l];
int i = l + 1;
int j = r;
while (i <= j) {
while (i <= j && nums[i] <= pivot) {
i++;
}
while (i <= j && nums[j] >= pivot) {
j--;
}
if (i > j) {
break;
}
swap(nums[i], nums[j]);
}
swap(nums[l], nums[j]);
return j;
}
};
归并排序
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
mergeSort(nums, 0, nums.size() - 1);
return nums;
}
void mergeSort(vector<int> &nums, int left, int right) {
if (left >= right) {
return;
}
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, mid, right); // 后序遍历
}
// 合并有序数组,类似合并有序链表
void merge(vector<int> &nums, int left, int mid, int right) {
vector<int> tmp;
int i = left;
int j = mid + 1;
while(i <= mid && j<= right) {
if (nums[i] < nums[j]) {
tmp.push_back(nums[i]);
i++;
} else {
tmp.push_back(nums[j]);
j++;
}
}
while(i <= mid) {
tmp.push_back(nums[i]);
i++;
}
while(j <= right) {
tmp.push_back(nums[j]);
j++;
}
for (int p = 0; p < right - left + 1; p++) {
nums[left + p] = tmp[p];
}
}
};