题目
给定一个整数数组 nums,将该数组升序排列。
链接:https://leetcode-cn.com/problems/sort-an-array/
示例 1:
输入:[5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:[5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
提示:
- 1 <= A.length <= 10000
- -50000 <= A[i] <= 50000
题解
采用快速排序
public static int[] sortArray(int[] nums) {
quickSort(nums,0,nums.length-1);
return nums;
}
public static void quickSort(int[] nums,int low,int high){
if (low<high){
int middle = getMiddle(nums,low,high);
//左子序列排序
quickSort(nums,low,middle-1);
//右子序列排序
quickSort(nums,middle+1,high);
}
}
private static int getMiddle(int[] nums, int low, int high) {
//取基准
int temp = nums[low];
while (low<high){
//取=的原因是保证相同数字的情况下排序任然继续
while (low < high && temp <= nums[high]){
high--;
}
nums[low] = nums[high];
while (low < high && temp >= nums[low]){
low++;
}
nums[high] = nums[low];
}
nums[low] = temp;
return low;
}