簡體   English   中英

兩個排序數組的中位數

[英]Median of two sorted array

在這里,我編寫了用於查找兩個已排序 arrays 的中位數的代碼:

#include<iostream>
using namespace std;
#define L  5
#define  M 6
 const int N=L+M;
int A[1000];//define 1 indexed aarray
int B[1000];
int max(int c,int d){
    return (c>=d)?c:d;

}
int min(int c,int d)
{
    return (c<=d)?c:d;
}

void  read(){
    cout<<" enter A array "<<endl;
    for (int i=1;i<=L;i++)
        cin>>A[i];
    cout<<endl;
    cout<<"enter B array  "<<endl;
    for (int i=1;i<=M;i++)
        cin>>B[i];
    cout<<endl;


}
int median(int a[],int b[],int left,int right){
    if (left>right) {
        return median(b,a,max(1,(N/2)-L),min(M,N/2));
    }
    int i=int(left+right)/2;
    int j=int(N/2)+i;
    if((j==0 || a[i]>b[j]) && (j==M || a[i]<=b[j+1])){
        return a[i];
    }
    else
    {
        if((j==0 || a[i]>b[j])  &&(j!=M && a[i]>b[j+1]))
        return median(a,b,left,i-1);
    }


        return median(a,b,i+1,right);

}

int main(){




    return 0;
}

我的問題是什么是左右值? 從介紹到算法,我只是不明白左右變量的值是什么? 我已將左右定義為 1 和 N,並使用以下 arrays 進行了測試:

3 5 7 9 11 13
1 2 4 8 10

答案是 13,這是不正確的肯定,什么是錯的?

您在評論中引用作業問題看起來似乎很好地解釋了leftright ,包括它們的起始值:

令left和right的默認值等於調用MEDIAN-SEARCH(A,B)等於

 MEDIAN-SEARCH(A[1 ..l],B[1 ..m],max(1,ceil(n/2) - m),min(l,ceil(n/2))) 

MEDIAN-SEARCH(A,B)的不變性是中位數始終在A[left ..right]B 對於初始調用而言,這是正確的,因為AB已排序,因此根據中位數的定義,它必須在max(1,ceil(n/2) - m)min(l,ceil(n/2)) ,包括的。 第8行和第9行的遞歸調用也是如此,因為該算法僅消除了中位數定義中不能成為中位數的數組部分。 第2行的遞歸調用也保留了不變性,因為如果left > right則中間值必須在新的leftright值之間的B

如果您在具有小陣列的紙上研究該算法,則應該更加清楚發生了什么。 如果您的數組小於等於16個元素的總數,則該算法僅需幾個步驟即可收斂,因此在紙上應該很可行。

請考慮以下

std::cout << "enter all number separated by a space ending with 'q'" 
          << std::endl;
std::vector<int> v(
    (std::istream_iterator<int>(std::cin)),
     std::istream_iterator<int>());

std::sort(v.begin(), v.end());
std::cout << "median value is: " 
          << std::advance(v.begin(), v.size()/2); 
          << std::endl;

這是使用mergesort的merge方法查找長度不相等的兩個排序數組的中位數的代碼

package FindMedianBetween2SortedArrays;

import java.util.Scanner;

public class UsingMergeMethodOfMergeSort {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try{
            System.out.println("Enter the number of elements in the first SORTED array");
            int n = in.nextInt();
            int[] array1 = new int[n];
            System.out.println("Enter the elements of the first SORTED array");
            for(int i=0;i<n;i++)
                array1[i]=in.nextInt();
            System.out.println("Enter the number of elements in the second SORTED array");
            int m = in.nextInt();
            int[] array2 = new int[m];
            System.out.println("Enter the elements of the second SORTED array");
            for(int i=0;i<m;i++)
                array2[i]=in.nextInt();
            System.out.println("Median of the two SORTED arrays is: "+findMedianUsingMergeOfMergeSort(array1,array2));
        }
        finally{
            in.close();
        }
    }
    private static int findMedianUsingMergeOfMergeSort(int[] a, int[] b) {

    /*  a1 array and a2 array can be of different lengths.
        For Example:
      1.
        a1.length = 3
        a2.length = 6
        totalElements = 3+6=9 (odd number)
      2.
        a1.length = 4
        a2.length = 4
        totalElements = 4+4=8 (even number)
    */
        int totalElements = a.length+b.length;  // totalElements is the addition of the individual array lengths
        int currentMedian = 0;
        int prevMedian = 0;
        int i=0; // Index for traversing array1
        int j=0; // Index for traversing array2
        for(int k=0;k<totalElements;k++){    // k is index for traversing the totalElements of array1 and array2


        /*NOTE: In this entire for loop, the "if", "else" and "else if" is VERY IMP. DONOT interchange among them*/

            // if array1 is exhausted
            if(i==a.length)
                currentMedian=b[j++]; // elements of the second array would be considered


            // if array2 is exhausted
            else if(j==b.length)
                currentMedian=a[i++]; // elements of the first array would be considered

            else if(a[i]<b[j])
                currentMedian=a[i++];

            else //(b[j]<=a[i])            // this condition is ONLY "else" and not "if" OR "else if"
                currentMedian=b[j++];

            if(k==totalElements/2) // we reached the middle of the totalElements where the median of the combined arrays is found
                break;                 

            prevMedian = currentMedian;

        }

        // if the totalElements are odd
        if(totalElements%2!=0)
            return currentMedian;
        else
            return (prevMedian+currentMedian)/2;
    }
}
/*
Analysis:
    Time Complexity = Linear Time, O((m+n)/2)
    Space Complexity = O(1)
*/
class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        double median;
        for(int i = 0; i<nums2.size();++i){
            nums1.push_back(nums2[i]);
        };
        sort(nums1.begin(),nums1.end());
        if(nums1.size()%2 == 0){
            median = (double)(nums1[(nums1.size()/2)-1] + nums1[nums1.size()/2])/2;
            
        }else{
            if(nums1.size() == 1) median = nums1[0];
            median = nums1[((nums1.size()/2) + (nums1.size()%2)) - 1];
        }
        return median;
        
};
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM