归并排序
class Solution2 {
public int[] sortArray(int[] nums) {
if (nums == null || nums.length == 0) return nums;
int[] temp = new int[nums.length];
mergeSort(nums, 0, nums.length - 1, temp);
return nums;
}
private void mergeSort(int[] nums, int start, int end, int[] temp) {
if (start >= end) {
return;
}
mergeSort(nums, start, (start + end) / 2, temp);
mergeSort(nums, (start + end) / 2 + 1, end, temp);
merge(nums, start, (start + end) / 2, end, temp);
}
private void merge(int[] nums, int start, int middle, int end, int[] temp) {
int leftStart=start, rightStart=middle+1;
int index=start;
while (leftStart<=middle && rightStart<=end){
if(nums[leftStart]<=nums[rightStart]) {
temp[index++]=nums[leftStart++];
}else {
temp[index++]=nums[rightStart++];
}
}
while (leftStart<=middle) {
temp[index++]=nums[leftStart++];
}
while (rightStart<=end++) {
temp[index++]=nums[rightStart++];
}
for(int i=start; i<=end; i++) {
nums[i]=temp[i];
}
}
}