Given an array of integers nums
, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Constraints:
1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000
思路:经典排序算法:merge sort和quick sort
class Solution {
// merge sort;
public int[] sortArray(int[] nums) {
if(nums == null || nums.length == 0) {
return nums;
}
return mergeSort(nums, 0, nums.length - 1);
}
private int[] mergeSort(int[] nums, int start, int end) {
if(start == end) {
return new int[]{nums[start]};
}
int mid = start + (end - start) / 2;
int[] left = mergeSort(nums, start, mid);
int[] right = mergeSort(nums, mid + 1, end);
return mergeTwoSortedArray(left, right);
}
private int[] mergeTwoSortedArray(int[] A, int[] B) {
int m = A.length; int n = B.length;
int i = 0; int j = 0;
int[] res = new int[m + n];
int index = 0;
while(i < m && j < n) {
if(A[i] < B[j]) {
res[index++] = A[i++];
} else {
res[index++] = B[j++];
}
}
while(i < m) {
res[index++] = A[i++];
}
while(j < n) {
res[index++] = B[j++];
}
return res;
}
}
quick sort,要熟悉两个while一个if的模板;这个要熟记,因为可以推展到quick select;
class Solution {
// quick sort;
public int[] sortArray(int[] nums) {
if(nums == null || nums.length == 0) {
return nums;
}
quickSort(nums, 0, nums.length - 1);
return nums;
}
private void quickSort(int[] nums, int start, int end) {
if(start >= end) {
return;
}
int mid = start + (end - start) / 2;
int pivot = nums[mid];
int i = start; int j = end;
while(i <= j) {
while(i <= j && nums[i] < pivot) {
i++;
}
while(i <= j && nums[j] > pivot) {
j--;
}
if(i <= j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;
j--;
}
}
// j, j + 1, i
quickSort(nums, start, j);
quickSort(nums, i, end);
}
}