查找两个有序数组中的第K个元素(find kth smallest element in 2 sorted arrays)

查找两个有序数组中的第K个元素

int FindKth(int a[], int b[], int k, int astart, int aend, int bstart, int bend)
{
    int aLen = aend - astart + 1;
    int bLen = bend - bstart + 1;

    if (aLen == 0)
    {
        return b[bstart + k];
    }

    if (bLen == 0)
    {
        return a[astart + k];
    }

    if (k == 0)
    {
        return a[astart] > b[bstart] ?  b[bstart] : a[astart] ;
    }

    int amid = aLen * k / (aLen + bLen); //按比例,算出分界点
    int bmid = k - amid - 1;

    amid += astart;
    bmid += bstart;

    if (a[amid] > b[bmid])
    {
        k -= (bmid - bstart + 1);
        aend = amid;
        bstart = bmid + 1;
    }
    else
    {
        k -= (amid - astart + 1);
        bend = bmid;
        astart = amid + 1;
    }
    return FindKth(a, b, k, astart, aend, bstart, bend);
}

int main(int argc, char* argv[])
{
    int a[] = {0, 1, 3, 5, 6, 8, 9};
    int b[] = {2, 10, 11, 13};

    printf("\nfind 0th it=%d\n", FindKth(a, b, 0, 0, 6, 0, 3));
    printf("\nfind 1th it=%d\n", FindKth(a, b, 1, 0, 6, 0, 3));
    printf("\nfind 2th it=%d\n", FindKth(a, b, 2, 0, 6, 0, 3));
    printf("\nfind 3th it=%d\n", FindKth(a, b, 3, 0, 6, 0, 3));
    printf("\nfind 4th it=%d\n", FindKth(a, b, 4, 0, 6, 0, 3));
    printf("\nfind 5th it=%d\n", FindKth(a, b, 5, 0, 6, 0, 3));
    printf("\nfind 6th it=%d\n", FindKth(a, b, 6, 0, 6, 0, 3));
    printf("\nfind 7th it=%d\n", FindKth(a, b, 7, 0, 6, 0, 3));
    printf("\nfind 8th it=%d\n", FindKth(a, b, 8, 0, 6, 0, 3));
    printf("\nfind 9th it=%d\n", FindKth(a, b, 9, 0, 6, 0, 3));
    printf("\nfind 10th it=%d\n", FindKth(a, b, 10, 0, 6, 0, 3));

    getchar();
    return 0;
}

 

posted on 2014-04-10 22:50  algorithmic  阅读(1498)  评论(0编辑  收藏  举报

导航