We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
function mergeSort(arr){ // 自上而下 let len=arr.length // 终止条件 if(len<2){ return arr } let middle=Math.floor(len/2) let left=arr.slice(0,middle) let right=arr.slice(middle) return merge(mergeSort(left),mergeSort(right)) } function merge(left,right){ let result=[] while(left.length&&right.length){ // = 保证排序稳定 if(left[0]<=right[0]){ result.push(left.shift()) }else{ result.push(right.shift()) } } while(left.length) result.push(left.shift()) while(right.length) result.push(right.shift()) return result }
The text was updated successfully, but these errors were encountered:
/** * @param {number[]} nums * @return {number[]} */ var sortArray = function(nums) { // 归并排序(二叉树的后序遍历) function sort(nums,l,h){ if(l==h){ return } let mid=l+Math.floor((h-l)/2) sort(nums,l,mid) sort(nums,mid+1,h) merge(nums,l,mid,h) } function merge(nums,l,mid,h){ let tmp=[] for (let i = l; i <= h; i++) { tmp[i] = nums[i]; } let i=l,j=mid+1 for(let p=l;p<=h;p++){ if(i==mid+1){ // 左边数组合并完成 nums[p]=tmp[j++] }else if(j==h+1){ // 右边数组合并完成 nums[p]=tmp[i++] }else if(tmp[i]<=tmp[j]){ nums[p]=tmp[i++] }else{ nums[p]=tmp[j++] } } } sort(nums,0,nums.length-1) return nums };
Sorry, something went wrong.
No branches or pull requests
思想
递归
分析
归并排序不是原地排序算法
归并排序是一种稳定的排序算法
归并排序的时间复杂度是O(nlogn),空间复杂度是O(n)
The text was updated successfully, but these errors were encountered: