shuffle可随机打乱数组
使用场景,例如常见的快速排序,当数组元素很对且基本有序时,时间复杂度会退化成o(n2)。优化方式有很多种,这里结合c++11特性shuffle()函数, 来优化快排时间复杂度
#include <iostream>
#include <algorithm>
#include <random>
using namespace std;
vector<int> sortArray(vector<int>& nums)
{
shuffle(begin(nums), end(nums), default_random_engine(random_device()()));
quicksort(nums, 0, nums.size()-1);
return nums;
}
void quicksort(vector<int>& nums, int low,int hei)
{
if(low>=hei)
return;
int par=partion(nums, low, hei);
quicksort(nums, low, par-1);
quicksort(nums, par+1, hei);
}
int partion(vector<int>& nums, int low, int hei)
{
int key=nums[low];
while(low<hei)
{
while(low< hei&& key <= nums[hei])
--hei;
nums[low]=nums[hei];
while(low< hei&& nums[low]<= key)
++low;
nums[hei]=nums[low];
}
nums[low]=key;
return low;
}