Search code examples
javaarraysfunctionparametersmedian

passing the result of a void function to a double function


I am trying to merge two sorted arrays in a void function 'merged' then pass the merged array from that function to 'findMedianSortedArray' to find the median of that merged array.

I am having trouble figuring out how to do this and have exhausted my search via google. how would I be able to do this? thanks for your help.

Code below

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2){ 
        int[] mergedArr = new int[nums1.length+nums2.length];
        double median;
        
        if(mergedArr.length %2 == 0 ){
            median = (mergedArr[mergedArr.length/2]+ mergedArr[mergedArr.length/2 - 1] ) /2;
        }else{
            median = mergedArr[mergedArr.length/2];
        }
        
        return median;
    }
    
    private void merged(int[] nums1, int[] nums2, int[] mergedArr){
        int i = 0;
        int j = 0;
        int k = 0;
       
        while(i < nums1.length && j < nums2.length){
            if(nums1[i]< nums2[j]){
                mergedArr[k] = nums1[i];
                i++;
            }else{
                mergedArr[k] = nums2[j];
                j++;
            }
            k++;
        }
        while(i < nums1.length ){
            mergedArr[k] = nums1[i];
            i++;
            j++;
        }
        while(j < nums2.length ){
            mergedArr[k] = nums2[j];
            i++;
            j++;
            
        }
    }
        
}

Solution

  • [1] your merged code is broken. It doesn't increment k in the second and third while loop.

    [2] Just.. call it:

    int[] mergedArr = new int[nums1.length+nums2.length];
    merged(nums1, nums2, mergedArr);
    

    The first line makes a new array, with nothing in it yet (all zeroes). The second line invokes the merged method, passing it all 3 arrays. The way your merged method works, is that it sets the values of the third array. Which is your mergedArr, so once merged returns, it'll have what you want.

    Ordinarily you'd instead write a method that returns int[], and have the merged method make that array. Your title is effectively an oxymoron: A void function, by definition, doesn't return anything. You've gone for the creative choice to have a method that modifies one of its arguments. It works; it's not exactly a modern coding style.