快速排序
1.将第一个元素作为pivot(为了防止顺序数组,随机选择一个换到第一个)
2.定义左右各一个指针
3.移动右指针,使得指针右边的element都大于pivot,同样使得左指针左边的element都小于pivot,直到两个指针指向同一个位置
4.交换pivot与当前指针指向的位置
5.为提防全部相同的数组,排除掉当前左右与当前pivot相同的element,不纳入考虑。
6.分别对左右两个数组进行快排
912.排序数组
给你一个整数数组 nums,请你将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
提示:
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
解决方案:
class Solution {
public:void quicksort(vector<int>& nums, int l, int r){if(l>=r) return;int ra = rand() % (r-l+1) + l;swap(nums[l], nums[ra]);int pivot = nums[l], i = l, j = r;while(i<j){while (nums[j]>pivot && j>i) j--;while(nums[i]<=pivot && i<j) i++;if (i < j)swap(nums[i], nums[j]);}swap(nums[l], nums[j]);int low = j-1, high = j+1;while(high < r && nums[high]==nums[j]) high++;while(low > l && nums[low]==nums[j]) low--;quicksort(nums, l, low);quicksort(nums, high, r);}vector<int> sortArray(vector<int>& nums) {quicksort(nums, 0, nums.size()-1);return nums;}
};