912. 排序数组
给你一个整数数组 nums,请你将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
提示:
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
代码
模板1
var sortArray = function(nums) {const quickSort = (l, r) => {if (l >= r) {return }let mid = nums[l + r >> 1], left = l - 1, right = r + 1while (left < right) {do {left ++} while(nums[left] < mid)do {right --} while (nums[right] > mid)if (left < right) {[nums[left], nums[right]] = [nums[right], nums[left]]}}quickSort(l, right)quickSort(right + 1, r)}quickSort(0, nums.length - 1)return nums
};
模板2
const quickSort = (arr) => {const solv = (arr) => {if (arr.length <= 1) return arr;const left = [];const right = [];const mid = arr[0];for (let i = 1; i < arr.length; i++)if (arr[i] < mid) left.push(arr[i]);else right.push(arr[i]);return [...solv(left), mid, ...solv(right)];};return solv(arr);
};
模板3
var sortArray = function(nums) {const quickSort = (arr) => {if (arr.length <= 1) return arrconst left = []const right = []const mid = arr[0]for (let i = 1; i < arr.length; i ++) {if (arr[i] < mid) left.push(arr[i])else right.push(arr[i])}const newLeft = quickSort(left)const newRight = quickSort(right)const newArr = []newLeft.forEach((item) => {newArr.push(item)})newArr.push(mid)newRight.forEach((item) => {newArr.push(item)})return newArr}const arr = quickSort(nums)return arr
};