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
参考 https://www.cnblogs.com/fatttcat/p/10058544.html
M1: Selection Sort, time = O(n^2), space = O(1), not stable
class Solution { public int[] sortArray(int[] nums) { if(nums == null || nums.length == 0) { return nums; } for(int i = 0; i < nums.length; i++) { int minIdx = i; for(int j = i + 1; j < nums.length; j++) { if(nums[j] < nums[minIdx]) { minIdx = j; } } int tmp = nums[i]; nums[i] = nums[minIdx]; nums[minIdx] = tmp; } return nums; } }
M2: Merge Sort, time = O(nlogn), space = O(n), stable
class Solution { public int[] sortArray(int[] nums) { if(nums == null || nums.length == 0) { return nums; } int[] helper = new int[nums.length]; mergeSort(nums, helper, 0, nums.length - 1); return nums; } private void mergeSort(int[] nums, int[] helper, int left, int right) { if(left >= right) { return; } int mid = left + (right - left) / 2; mergeSort(nums, helper, left, mid); mergeSort(nums, helper, mid + 1, right); merge(nums, helper, left, mid, right); } private void merge(int[] nums, int[] helper, int left, int mid, int right) { for(int i = left; i <= right; i++) { helper[i] = nums[i]; } int p1 = left, p2 = mid + 1, p = left; while(p1 <= mid && p2 <= right) { if(helper[p1] <= helper[p2]) { nums[p++] = helper[p1++]; } else { nums[p++] = helper[p2++]; } } while(p1 <= mid) { nums[p++] = helper[p1++]; } while(p2 <= right) { nums[p++] = helper[p2++]; } } }
M3: Quick Sort, average time = O(nlogn), worst time = O(n^2), space = O(logn), not stable
class Solution { public int[] sortArray(int[] nums) { if(nums == null || nums.length == 0) { return nums; } quickSort(nums, 0, nums.length - 1); return nums; } public void quickSort(int[] nums, int left, int right) { if(left >= right) { return; } Random r = new Random(); int pivot_idx = left + r.nextInt(right - left + 1); int pivot = nums[pivot_idx]; swap(nums, pivot_idx, right); int i = left, j = right - 1; while(i <= j) { if(nums[i] < pivot) { i++; } else { swap(nums, i, j--); } } swap(nums, i, right); quickSort(nums, left, i - 1); quickSort(nums, i + 1, right); } public void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }