Nth large number of two ordered arrays

Source: Internet
Author: User

Two ordered arrays, each containing n elements, calculate the nth Element

1. traverse two arrays sequentially, count the smallest K element in K statistics, and the time complexity is O (n)

The Code is as follows:

 
Int getmid (int A [], int B [], int N) {int K = 0; int I = 0, j = 0; while (I <n & J <n) {if (a [I] <B [J]) {I ++; k ++; If (k = N) return a [I-1];} else {J ++; k ++; If (k = N) return B [J-1] ;}}

2. Binary method

Take the middle element mid1 of array A, take the middle element mid2 of array B, and first compare the size of the two elements. If the two elements are equal, a [mid1] is returned directly. if a [mid1] <B [mid2], the elements on the left of mid1 can be removed, while those on the Right of array B can be removed. The number of elements in the array must be an even odd number, if the number of elements is an even number, the mid1 element should also be removed. This is similar if a [mid1] <B [mid2. The time complexity is O (logn)

 
# Include <iostream> # include <cstdlib> using namespace STD; int mid (int A [], int B [], int N) {int S1 = 0, e1 = n-1; int S2 = 0, E2 = n-1; int mid1 = (S1 + E1)/2; int mid2 = (s2 + e2)/2; while (S1! = E1 | S2! = E2) {mid1 = (S1 + E1)/2; mid2 = (s2 + e2)/2; if (a [mid1] = B [mid2]) {return a [mid1];} if (a [mid1] <B [mid2]) {If (S1 + E1) % 2 = 0) {S1 = mid1; e2 = mid2;} else {S1 = mid1 + 1; E2 = mid2;} else {If (S1 + E1) % 2 = 0) {e1 = mid1; s2 = mid2;} else {e1 = mid1; S2 = mid2 + 1 ;}} return a [S1] <B [s2]? A [S1]: B [s2];} int main () {int A [5] = {2, 4, 5, 6, 9}; int B [5] = {1, 3, 7, 8, 10}; cout <mid (A, B, 5) <Endl; System ("pause"); Return 0 ;}

Nth large number of two ordered arrays

Contact Us

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.