说明:使用递归及非递归两种方式实现快速排序
- 排序数组
给你一个整数数组 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 <= 50000
-50000 <= nums[i] <= 50000
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
quickSort2(nums);
return nums;
}
// 递归版本
void quickSort1(vector<int>& nums, int start, int end) {
if (start >= end) {
return;
}
int mid = nums[start];
int left = start, right = end;
while (left < right) {
while (left < right && nums[right] >= mid) --right;
nums[left] = nums[right];
while (left < right && nums[left] <= mid) ++left;
nums[right] = nums[left];
}
nums[left] = mid;
quickSort1(nums, start, left - 1);
quickSort1(nums, left + 1, end);
}
// 非递归版本
void quickSort2(vector<int>& nums) {
stack<int> st;
st.push(0);
st.push(nums.size() - 1);
int start = 0, end = 0;
while(!st.empty()) {
int end = st.top();
st.pop();
int start = st.top();
st.pop();
int mid = nums[start];
int left = start, right = end;
while (left < right) {
while (left < right && nums[right] >= mid) --right;
nums[left] = nums[right];
while (left < right && nums[left] <= mid) ++left;
nums[right] = nums[left];
}
nums[left] = mid;
if (start < left - 1) {
st.push(start);
st.push(left - 1);
}
if (left + 1 < end) {
st.push(left + 1);
st.push(end);
}
}
}
};
用时:33min,但是这两种快排写法在大数组的测试case都超时了。。。继续研究一下为什么。