给你一个整数数组 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 {
int[] nums;
public int[] sortArray(int[] nums) {
int n = nums.length;
this.nums = nums;
quick_sort(nums,0,n-1);
return nums;
}
public void quick_sort(int[] nums, int l, int r){
if(l >= r) return;
int x = nums[l+r >> 1];
int i = l-1, j = r+1;
while(i < j){
do i++; while(nums[i] < x);
do j--; while(nums[j] > x);
if(i < j){
int tem = nums[i];
nums[i] = nums[j];
nums[j] = tem;
}
}
quick_sort(nums,l,j);
quick_sort(nums,j+1,r);
}
}
归并排序
class Solution {
int[] nums;
int[] tem;
public int[] sortArray(int[] nums) {
int n = nums.length;
this.nums = nums;
tem = new int[n];
merge_sort(nums,0,n-1);
return nums;
}
public void merge_sort(int[] nums, int l, int r){
if(l >= r) return;
int mid = l+r >> 1;
merge_sort(nums,l,mid);
merge_sort(nums,mid+1,r);
int i = l, j = mid+1, k = 0;
while(i <= mid && j <= r)
if(nums[i] <= nums[j]) tem[k++] = nums[i++];
else tem[k++] = nums[j++];
while(i <= mid) tem[k++] = nums[i++];
while(j <= r) tem[k++] = nums[j++];
for(i = l, j = 0; i <= r; ++i,++j) nums[i] = tem[j];
}
}