题解
- 快速排序可以通过随机选取基准值来优化一些较极端的情况,使得时间复杂度控制在O(NlogN)
- 堆排序是可以处理的重复数据的哦
代码
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
// 堆排序 创建大根堆 向下调整法
HeapSort(nums);
return nums;
}
void AdjustDown(vector<int>& nums, int pos, int size)
{
int parent = pos;
int child = 2 * parent + 1;
if(child + 1 < size) child = nums[child] > nums[child + 1] ? child : child + 1;
while(child < size)
{
if(nums[parent] < nums[child])
{
std::swap(nums[parent], nums[child]);
parent = child;
child = 2 * parent + 1;
if(child + 1 < size) child = nums[child] > nums[child + 1] ? child : child + 1;
}
else break;
}
}
void HeapSort(vector<int>& nums)
{
int size = nums.size();
// 创建大根堆
int lastParent = (nums.size() - 2) / 2;
for(int i = lastParent; i >= 0; i--)
{
AdjustDown(nums, i, size);
}
// 堆排序
for(int i = 0; i < size - 1; i++)
{
std::swap(nums[0], nums[size - 1 - i]);
AdjustDown(nums, 0, size - 1 - i);
}
}
};
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
// 快速排序:随机选取基准数进行优化
srand(time(nullptr));
QuickSort(nums, 0, nums.size() - 1);
return nums;
}
void RandomOptimize(vector<int>& nums, int left, int right)
{
int index = rand() % (right - left + 1) + left;
std::swap(nums[left], nums[index]);
}
void QuickSort(vector<int>& nums, int left, int right)
{
if(left >= right) return;
RandomOptimize(nums, left, right);
int key = nums[left];
int l = left, r = right;
while(l < r)
{
while(r > l && nums[r] >= key) r--;
if(r == l) break;
while(l < r && nums[l] <= key) l++;
if(l < r) std::swap(nums[l], nums[r]);
}
std::swap(nums[l], nums[left]);
QuickSort(nums, left, l - 1);
QuickSort(nums, l + 1, right);
}
};