题目:力扣
class Solution {
public int[] sortArray(int[] nums) {
if(nums.length<=1){
return nums;
}
//quicksort(nums,0,nums.length-1);
mergesort(nums,0,nums.length-1);
return nums;
}
public int Partition(int[] nums,int start, int end){
int base = nums[start];
while(end>start){
while(end>start && nums[end]>=base){
end--;
}
nums[start]=nums[end];
while(end>start && nums[start]<=base){
start++;
}
nums[end]= nums[start];
}
nums[start]=base;
return start;
}
public void quicksort(int[] nums,int start, int end){
if(end>start){
int p = Partition(nums, start,end);
quicksort(nums,start,p-1);
quicksort(nums,p+1,end);
}
}
public void mergesort(int[] nums, int start, int end){
if(start>=end)
return;
int mid = (start+end)/2;
mergesort(nums, start, mid);
mergesort(nums, mid+1, end);
int[] temp = new int[end-start+1];
int first = start;
int second = mid+1;
int cur = 0;
while(first <= mid && second <=end){
if(nums[first]<nums[second]){
temp[cur++]=nums[first++];
}
else{
temp[cur++]=nums[second++];
}
}
while(first <= mid){
temp[cur++]= nums[first++];
}
while(second <= end){
temp[cur++]= nums[second++];
}
for (int k = 0; k < temp.length; k++) { // 合并数组完成,拷贝到原来的数组中
nums[start+k] = temp[k];
}
}
}