Why my merge sort output[1,0] for test[1,0]?


  • 0
    B
    public void sortColors(int[] nums) {
         nums = sortColors(nums, 0, nums.length-1);
    }
    public int[] sortColors(int[] nums, int low, int hi){
        //merge sort
        int mid = low +(hi-low)/2;
        if(low == hi){
            int[] t = new int[1];
            t[0] = nums[low];
            return t;
        }
        //divide
        int[] nums1 = sortColors(nums,low,mid);
        int[] nums2 = sortColors(nums,mid+1,hi);
        //merege
        return merge(nums1,nums2);
    }
    public int[] merge (int[] nums1, int[] nums2){
        int i = 0, j =0, k=0;
        int len1= nums1.length, len2= nums2.length;
        int [] res = new int[len1+len2];
        while(i<len1&&j<len2){
            if(nums1[i]<=nums2[j])
                res[k++] = nums1[i++];
            else 
                res[k++] = nums2[j++];
        }
        while(i<len1){res[k++] = nums1[i++];}
        while(j<len2){res[k++] = nums2[j++];}
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.