问题描述
Given an array of integers nums, sort the array in ascending order.
测试样例
1 2
| Input: nums = [5,2,3,1] Output: [1,2,3,5]]
|
1 2
| Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5]
|
说明
1 2
| 1 <= nums.length <= 5 * 10^4 -5 * 10^4 <= nums[i] <= 5 * 10^4
|
解题
思路
- 插入排序 O(n^2)
- 冒泡排序 O(n^2)
- 选择排序 O(n^2)
- 快排 O(nlogn)
- 归并排序 O(nlogn)
补充:
- 插入/冒泡/选择排序复杂度较高,会超时,这里仅实现
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| class Solution { public int[] sortArray(int[] nums) { int[] temp = new int[nums.length]; mergeSort(nums, 0, nums.length, temp); return nums; }
public int[] insertionSort(int[] nums) { for(int i=0; i<nums.length; ++i) { for(int j=i; j>0 && nums[j-1] > nums[j]; --j) { swap(nums, j, j-1); } } return nums; }
public int[] bubbleSort(int[] nums) { for(int i=1; i<nums.length; ++i) { boolean swapped = false; for(int j=1; j<nums.length-i+1; ++j) { if(nums[j] < nums[j-1]) { swap(nums, j, j-1); swapped = true; } } if(!swapped) break; } return nums; }
public int[] selectionSort(int[] nums) { for(int i=0; i<nums.length; ++i) { int idx_sorting = i; for(int j=i+1; j<nums.length; ++j) { if(nums[idx_sorting] > nums[j]) { idx_sorting = j; } } swap(nums, i, idx_sorting); } return nums; }
public void quickSort(int[] nums, int l, int r) { if(l >= r) { return; } int beg = l, end = r; int elem_sorting = nums[l]; while(beg < end) { while(beg < end && nums[end] >= elem_sorting) { --end; } nums[beg] = nums[end]; while(beg < end && nums[beg] < elem_sorting) { ++beg; } nums[end] = nums[beg]; } nums[beg] = elem_sorting; quickSort(nums, l, beg - 1); quickSort(nums, beg + 1, r); }
public void mergeSort(int[] nums, int l, int r, int[] temp) { if(l + 1 >= r) { return; } int mid = (l + r) / 2; mergeSort(nums, l, mid, temp); mergeSort(nums, mid, r, temp); int p1 = l, p2 = mid, idx = l; while(p1 < mid || p2 < r) { if(p2 >= r || (p1 < mid && nums[p1] <= nums[p2])) { temp[idx++] = nums[p1++]; } else { temp[idx++] = nums[p2++]; } } for(int i=l; i<r; ++i) { nums[i] = temp[i]; } }
public void swap(int[] arrays, int idx_a, int idx_b) { int elem = arrays[idx_a]; arrays[idx_a] = arrays[idx_b]; arrays[idx_b] = elem; } }
|