给你一个整数数组 nums,请你将该数组升序排列。
快速排序
class Solution {
public:
size_t partition(vector<int>& nums, size_t lo, size_t hi)
{
//升序
swap(nums[hi], nums[lo + rand()%(hi-lo+1)]);
int privt = nums[hi];
int i = lo - 1;
for(int j = lo;j <= hi -1;++j)
{
if(nums[j] <= privt)
{
swap(nums[++i],nums[j]);
}
}
swap(nums[++i],nums[hi]);
return i;
}
void qsort(vector<int>& nums,size_t lo, size_t hi)
{
if(hi - lo <2)return;
size_t mid = partition(nums, lo, hi - 1);
qsort(nums,lo, mid);
qsort(nums,mid + 1,hi);
}
vector<int> sortArray(vector<int>& nums) {
srand((unsigned)time(NULL));
qsort(nums,0, nums.size());
return nums;
}
};
另一种实现
class Solution {
public:
size_t partition(vector<int>& nums, size_t lo, size_t hi)
{
while(lo < hi)
{
while(lo<hi)
{
if(nums[hi] <= privt)
{
nums[lo++] = nums[hi];
break;
}
else
{
--hi;
}
}
while(lo<hi)
{
if(nums[lo] >= privt)
{
nums[hi--] = nums[lo];
break;
}
else
{
++lo;
}
}
}
nums[lo] = privt;
return lo;
}
另外:降序的实现
size_t partition(vector<int>& nums, size_t lo, size_t hi)
{
//降序
swap(nums[lo], nums[lo + rand()%(hi-lo+1)]);
int privt = nums[lo];
int i = hi+1;
for(size_t j = hi;j>lo;--j)
{
if(nums[j]<=privt)
{
--i;
swap(nums[i],nums[j]);
}
}
swap(nums[--i],nums[lo]);
return i;
}