double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
        
    double ldRslt = 0.0;        // return value
    int liMergedSize = 0;     // merged array size
    int liMerging[2000];  // array for merging two sorted arrays
    
    memset(liMerging, 0x00, sizeof(liMerging));
    
    int i=0; // index of nums1
    int j=0; // index of nums2
    int k=0; // index of merged array
    int nums1N = 0; // element of nums1
    int nums2N = 0; // element of nums2
    
    /* all out of index, then break */
    while( i < nums1Size || j < nums2Size )
    {
        /* nums1 out of index, then set 9999999 */
        if( i >= nums1Size )
        {
            nums1N = 9999999;
        }
        else
        {
            nums1N = nums1[i];
        }
        
        if( j >= nums2Size )
        {
            nums2N = 9999999;
        }
        else
        {
            nums2N = nums2[j];
        }
        
        if( nums1N < nums2N )
        {
            liMerging[k++] = nums1N;
            i++;
        }
        else
        {
            liMerging[k++] = nums2N;
            j++;
        }
    }
    
    liMergedSize = k;
    
    int liMidIdx = liMergedSize / 2;
    
    if( liMergedSize % 2 == 0 )
    {
        ldRslt = ( liMerging[liMidIdx-1] + liMerging[liMidIdx] ) / 2.0;
    }
    else
    {
        ldRslt = liMerging[liMidIdx];
    }
    
    return ldRslt;
}

 

두 개의 정렬된 integer array를 사용하여 중간값을 구하는 함수.

두 배열을 합쳐 한개의 정렬된 배열로 만들어 중간값을 구한다.

중간값은 배열 개수가 짝수인 경우는 가운데 두 수의 평균값으로, 홀수인 경우는 가운데 수로 출력한다.

 

깃허브 주소:

https://github.com/binary-river/algorithms/blob/Master/medianOfTwoSortedArray.c

 

GitHub - binary-river/algorithms: algorithms practices

algorithms practices. Contribute to binary-river/algorithms development by creating an account on GitHub.

github.com

 

+ Recent posts