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]
解题:
var sortArray = function (nums) {
const swap = (i, j) => {
const temp=nums[i]
nums[i]=nums[j]
nums[j]=temp
};
const temp=[]
const marge = (left, mid, right)=>{
let p1=left,p2=mid+1;
temp.length=0
while(p1<=mid&&p2<=right){
temp.push(nums[p1]<nums[p2]?nums[p1++]:nums[p2++])
}
while(p1<=mid){
temp.push(nums[p1++])
}
while(p2<=right){
temp.push(nums[p2++])
}
for(let i=left;i<=right;i++){
nums[i]=temp[i-left]
}
};
const sort = (left, right) => {
if(left>=right)return
if((right-left===1)&&nums[left]>nums[right]){
swap(left,right)
return
}
const mid=left+((right-left)>>1)
sort(left,mid)
sort(mid+1,right)
marge(left,mid,right)
};
sort(0, nums.length - 1);
return nums;
};