题目
给你一个整数数组 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
用来复习快速排序、归并排序、堆排序的写法。快速排序用了随机 pivot 的写法尽量避免最坏时间复杂度。
平均时间复杂度: O ( n log n ) O(n\log n) O(nlogn)
空间复杂度:
- 快速排序: O ( log n ) O(\log n) O(logn) ~ O ( n ) O(n) O(n)(递归调用需要空间)
- 归并排序: O ( n ) O(n) O(n)
- 堆排序:理论上是 O ( 1 ) O(1) O(1),我的代码为了下标处理方便,写成了 O ( n ) O(n) O(n)
C++ 代码
快速排序
class Solution {
public:
int partition(vector<int>& nums, int left, int right) {
int temp = nums[left];
while (left < right) {
while (left < right && nums[right] > temp)
--right;
nums[left] = nums[right];
while (left < right && nums[left] <= temp)
++left;
nums[right] = nums[left];
}
nums[left] = temp;
return left;
}
int randomizedPartition(vector<int>& nums, int left, int right) {
int i = rand() % (right - left + 1);
swap(nums[left], nums[left + i]);
return partition(nums, left, right);
}
void quickSort(vector<int>& nums, int left, int right) {
if (left < right) {
int pos = randomizedPartition(nums, left, right);
quickSort(nums, left, pos - 1);
quickSort(nums, pos + 1, right);
}
}
vector<int> sortArray(vector<int>& nums) {
srand((unsigned)time(nullptr));
quickSort(nums, 0, nums.size() - 1);
return nums;
}
};
归并排序(非递归)
class Solution {
public:
vector<int> sortArray(vector<int>& nums) {
if (nums.size() < 2)
return nums;
int size = nums.size();
for (int step = 2; step <= 2 * size; step <<= 1) {
for (int lo = 0; lo < size; lo += step) {
int mid = lo + (step >> 1), hi = min(size, mid + (step >> 1));
if (mid >= size)
continue;
merge(nums, lo, mid, hi);
// printf("merge(nums, %d, %d, %d);\n", lo, mid, hi);
}
}
return nums;
}
// 归并nums数组中的[lo, mid)和[mid, hi)范围
void merge(vector<int>& nums, int lo, int mid, int hi) {
vector<int> result;
int p = lo, q = mid;
while (p < mid && q < hi) {
if (nums[p] < nums[q])
result.push_back(nums[p++]);
else
result.push_back(nums[q++]);
}
while (p < mid)
result.push_back(nums[p++]);
while (q < hi)
result.push_back(nums[q++]);
copy(result.begin(), result.end(), nums.begin() + lo);
}
};
堆排序
class Solution {
public:
int pop(vector<int>& heap) {
if (heap.size() < 2)
return 0;
int ret = heap[1];
heap[1] = heap.back();
heap.pop_back();
downAdjust(heap, 1);
return ret;
}
void downAdjust(vector<int>& heap, int hole) {
int tmp = heap[hole];
int index = hole * 2;
while (index < heap.size()) {
if (index + 1 < heap.size() && heap[index + 1] < heap[index])
++index;
if (heap[index] < tmp) {
swap(heap[index / 2], heap[index]);
index *= 2;
} else {
break;
}
}
}
vector<int> sortArray(vector<int>& nums) {
// 建堆
vector<int> heap(nums.size() + 1);
heap[0] = 0;
copy(nums.begin(), nums.end(), heap.begin() + 1);
for (int i = heap.size() / 2; i >= 1; --i)
downAdjust(heap, i);
// 不断pop,构建答案
vector<int> ans;
while (heap.size() > 1)
ans.push_back(pop(heap));
return ans;
}
};