1.快速排序(随机)
快速排序的时间复杂度为, 最坏情况为
,而随机快速排序的期望时间复杂度为O(n)。或许还要种个时间的种子 srand(unsigned(time(NULL)));
void quickSort(vector<int> &nums, int L, int R)
{
if (L >= R) return;
int id = rand() % (R - L + 1) + L;
int pivot = nums[id];
swap (nums[R], nums[id]);
int low = L - 1, high = R;
for(int i = L; i < high; )
{
if (nums[i] < pivot)
{
swap(nums[i], nums[low + 1]);
++low, ++i;
}
else if (nums[i] > pivot)
{
swap(nums[i], nums[high - 1]);
--high; //此时不用++i,因为从后面来的数还没看过
}
else
++i;
}
swap(nums[R], nums[high]);
quickSort(nums, L, low);
quickSort(nums, high + 1, R);
}
2.堆排序
堆排序的核心代码就是heapAdjust部分,就是不断下调节点操作。
class Solution {
void heapAdjust(vector<int> &nums, int parent, int len)
{
int id = parent;
int L = id * 2 + 1, R = id * 2 + 2;
if (L < len && nums[id] < nums[L])
id = L;
if (R < len && nums[id] < nums[R])
id = R;
if (id != parent)
{
swap(nums[id], nums[parent]);
heapAdjust(nums, id, len);
}
return;
}
void heapSort(vector<int> &nums)
{
int len = nums.size();
for (int i = len / 2 - 1; i >= 0; --i) //build head
{
heapAdjust(nums, i, len);
}
for (int i = len - 1; i >= 0; --i)
{
swap(nums[i], nums[0]);
heapAdjust(nums, 0, i);
}
}
};