Given an array of integers nums, sort the array in ascending order and return it. You must solve the problem without using any built-in functions in $O(nlog(n))$ time complexity and with the smallest space complexity possible. Example 1:
Input: nums = [5,2,3,1] Output: [1,2,3,5] Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
2. Bubble Sort
classSolution { publicint[] sortArray(int[] nums) { for (inti= nums.length-1; i > 0; i--) { for (intj= i-1; j >= 0; j--) { if (nums[j] > nums[i]) { swap(nums, i, j); } } } return nums; }
privatevoidswap(int[] nums, int i, int j) { intt= nums[i]; nums[i] = nums[j]; nums[j] = t; } }
3. Insertion Sort
classSolution { publicint[] sortArray(int[] nums) { for (inti=1; i < nums.length; i++) { for (intj= i-1; j >= 0; j--) { if (nums[j] > nums[j+1]) { swap(nums, j, j+1); } else { break; } } } return nums; }
privatevoidswap(int[] nums, int i, int j) { intt= nums[i]; nums[i] = nums[j]; nums[j] = t; } }
privatevoidmergeSort(int[] nums, int l, int r) { if (l == r) return; intm= l + (r - l) / 2; mergeSort(nums, l, m); mergeSort(nums, m+1, r); merge(nums, l, m, r); }
privatevoidmerge(int[] nums, int l, int m, int r) { intp1= l, p2 = m+1, i = 0; int[] t = newint[r - l + 1]; while (p1 <= m && p2 <= r) t[i++] = nums[p1] < nums[p2] ? nums[p1++] : nums[p2++]; while (p1 <= m) t[i++] = nums[p1++]; while (p2 <= r) t[i++] = nums[p2++]; for (i = 0; i < t.length; i++) { nums[l+i] = t[i]; } } }
privatevoidquickSort(int[] nums, int l, int r) { if (l >= r) return; int[] p = partition(nums, l, r); quickSort(nums, l, p[0]-1); quickSort(nums, p[1]+1, r); }
privateint[] partition(int[] nums, int l, int r) { intless= l, more = r-1, i = l; swap(nums, l+rand.nextInt(r-l+1), r); while (i <= more) { if (nums[i] < nums[r]) { swap(nums, i++, less++); } elseif (nums[i] > nums[r]) { swap(nums, i, more--); } else { i++; } } swap(nums, more+1, r); returnnewint[]{less, more}; }
privatevoidswap(int[] nums, int i, int j) { intt= nums[i]; nums[i] = nums[j]; nums[j] = t; } }
6. Heap Sort
classSolution { publicint[] sortArray(int[] nums) { for (inti=1; i < nums.length; i++) { insert(nums, i); } for (inti= nums.length-1; i > 0; i--) { swap(nums, 0, i); heapify(nums, 0, i); } return nums; }
privatevoidinsert(int[] nums, int i) { intp= (i - 1) / 2; while (nums[p] < nums[i]) { swap(nums, p, i); i = p; p = (i - 1) / 2; } }
privatevoidheapify(int[] nums, int i, int size) { intl=2 * i + 1; // left child while (l < size) { intlargest= l+1 < size && nums[l+1] > nums[l] ? l+1 : l; if (nums[largest] <= nums[i]) break; swap(nums, i, largest); i = largest; l = 2 * i + 1; } }
privatevoidswap(int[] nums, int i, int j) { intt= nums[i]; nums[i] = nums[j]; nums[j] = t; } }