Given an array of integers nums
, sort the array in ascending order.
Example 1:
Input: [5,2,3,1] Output: [1,2,3,5]
Example 2:
Input: [5,1,1,2,0,0] Output: [0,0,1,1,2,5]
Note:
1 <= A.length <= 10000
-50000 <= A[i] <= 50000
快速排序:
class Solution {
public int[] sortArray(int[] nums) {
shuffle(nums);//避免最坏情况
sortArray(nums,0,nums.length-1);
return nums;
}
private void sortArray(int[] nums,int low,int high){
if(low>=high) return;
int j = patrition(nums,low,high);//nums[j]已经在合适的位置上了
sortArray(nums,low,j-1);
sortArray(nums,j+1,high);
}
private int patrition(int[] nums,int low,int high){
int i = low;
int j = high+1;
while(true){
while(nums[++i]<nums[low]){
if(i==high) break;
}
while(nums[--j]>nums[low]){
}
if(i>=j) break;
swap(nums,i,j);
}
swap(nums,low,j);
return j;
}
private void shuffle(int[] nums){
Random random = new Random();
for(int i = 1;i<nums.length;i++){
int r = random.nextInt(i+1);
swap(nums,r,i);
}
}
private void swap(int[] nums,int i ,int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}