Median of two sorted Arrays

Source: Internet
Author: User

There are two sorted arrays A and B of size M and N respectively. find the median of the two sorted arrays. the overall run time complexity shoshould be O (log (m + n )).

` 1 public class Solution { 2     public double findMedianSortedArrays(int A[], int B[]) { 3         int alen = A.length; 4         int blen = B.length; 5         if((alen + blen) % 2 == 1) return findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 1) / 2); 6         else return (double) (findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen) / 2) + findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 2) / 2)) / 2.0; 7     } 8     private int findKthElement(int arra[], int arrb[], int ast, int and, int bst, int bnd, int num){ 9         if(ast > and) return arrb[bst + num - 1];10         if(bst > bnd) return arra[ast + num - 1];11         int amid = (ast + and) / 2;12         int bmid = (bst + bnd) / 2;13         int len = amid - ast + 1 + bmid - bst + 1;14         if(arra[amid] < arrb[bmid]){15             if(len <= num) return findKthElement(arra, arrb, amid + 1, and, bst, bnd, num - amid + ast - 1);16             else return findKthElement(arra, arrb, ast, and, bst, bmid - 1, num);17         }else{18             if(len <= num) return findKthElement(arra, arrb, ast, and, bmid + 1, bnd, num - bmid + bst - 1);19             else return findKthElement(arra, arrb, ast, amid - 1, bst, bnd, num);20         }21     }22 }`

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• Sales Support

1 on 1 presale consultation

• After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.