给你一个整数数组 nums
,请你将该数组升序排列。
示例 1:
1 2
| 输入:nums = [5,2,3,1] 输出:[1,2,3,5]
|
示例 2:
1 2
| 输入:nums = [5,1,1,2,0,0] 输出:[0,0,1,1,2,5]
|
提示:
1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000
个人解答
冒泡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
var sortArray = function(nums) { var len = nums.length; for (var i = len - 1; i > 0; i--) { for (var j = 0; j < i; j++) { if (nums[i] < nums[j]) { var temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } return nums; };
|
快排
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var sortArray = function(nums) { return quickSort(nums); };
function quickSort (nums) { if (nums.length <= 1) { return nums; } else { var biggers = []; var base = nums[0]; var smallers = []; for (var i = 1; i < nums.length; i++) { if (nums[i] > base) { biggers.push(nums[i]); } else { smallers.push(nums[i]); } } return [ ...quickSort(smallers), base, ...quickSort(biggers) ]; } }
|
解题思路
纯排序题,写了两种我自己比较擅长的 ==。