算法实验1 两个数组的中位数

// test.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <type_traits>
using namespace std;



int midSearch(int a[], int b[],int na,int nb) {
    int a_l = na;
    int b_l = nb;
    int *temp = new int[a_l + b_l + 1];
    int i = 0, j = 0, t = 0;
    while (i < a_l && j < b_l) {
        if (a[i] <= b[j])temp[t++] = a[i++];
        else temp[t++] = b[j++];
    }

    while (i < a_l)temp[t++] = a[i++];
    while (j < b_l)temp[t++] = b[j++];

    //for (int i = 0; i < a_l + b_l; i++)cout << temp[i];
    int l = a_l + b_l;
    if (l % 2 == 0) 
        return((temp[l / 2-1] + temp[l / 2 ]) / 2);//注意数组下标从0开始
    else return(temp[l / 2 ]);
    

}

int main()
{
    int a[] = { 1,2,3 };
    int b[] = { 4,5};
    cout<<midSearch(a, b,3,2);
        return 0;
}

 

posted @ 2019-02-28 15:22  Kiss_the_rain  阅读(159)  评论(0编辑  收藏  举报