有经验的的读者应该会有警觉性,这颗递归树在一些特殊数据情况下很有可能会由树 退化成链。从而使 O(nlogn) 的复杂度退化到 O(n^2)。
这样我们快速排序的效果就大打折扣了。
为了解决这个问题我们回到我们之前的处理方式,我们是直接选取问题序列的第一个元素的。因此很容易发现当数据是有序,或者重复数值很多的时候递归树就会往单个方向退化。因此我们可以使用 随机选点的方式,来使数据不会一边倒的集中。

例题
最后我们来一道排序数组的模板题作为练习。
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
srand((unsigned)time(NULL));
quickSort(nums, 0, nums.size() - 1);
return nums;
}
private:
void quickSort(vector<int>& arr, const int first, const int last) {
if (first >= last) {
return;
}
// (优化)随机取一个数
int randIdx = first + (rand() % (last - first + 1));
swap(arr[randIdx], arr[first]);
int left = first;
int right = last;
int border = arr[left];
while (left < right) {
while (left < right && border <= arr[right]) {
right += -1;
}
arr[left] = arr[right];
while (left < right && border >= arr[left]) {
left += 1;
}
arr[right] = arr[left];
}
arr[left] = border;
const int borderIdx = left;
quickSort(arr, first, borderIdx - 1);
quickSort(arr, borderIdx + 1, last);
}
};
今天的文章分享到这里就结束了,希望认真阅读全文的小伙伴,都能有所收获哦!