算法分析与设计实验-中位数问题

分治法解决中位数问题实验

问题描述

设X[ 0 : n - 1]和Y[ 0 : n – 1 ]为两个数组,每个数组中含有n个已排好序的数。找出X和Y的2n个数的中位数。利用分治策略试设计一个O (log n)时间的算法求出这2n个数的中位数。
由文件input.txt提供输入数据,文件的第1行中有1个正整数n(n<=200),表示每个数组有n个数。接下来的两行分别是X,Y数组的元素。。程序运行结束时,将计算出的中位数输出到文件output.txt中

实验设计

fstream f(“D://算法分析与设计/input.txt”);读取文件
istringstream is1(row2);配合stoi(),根据空格解析字符串到数组a和b中
递归算法求中位数算法:
temp(int *a, int *b, int size){
m为两数组中间位置
if (两数组中位数相等) {
return a[m];直接返回
}
else if (a数组中位数>b数组中位数) {
取a数组前半段,取b数组后半段,进行递归。
当数组长度为1,直接返回b
}
else
{
取b数组前半段,取a数组后半段,进行递归。
当数组长度为1,直接返回a

	}

}

ofstream of("D://算法分析与设计/output.txt"); //写入output.txt文件。

程序结束。

实验代码

#include <iostream>
#include<fstream>
#include<cstring>
#include<sstream>
using namespace std;
int  temp(int *a, int *b, int size) {
	
		int m = (size - 1) / 2;  //中间位置
		if (a[m] == b[m]) {  //如果相等,直接返回
			return a[m];
		}
		else if (a[m] > b[m]) {   //如果a>b,则位于a的前半段,b的后半段,用这2段继续递归
			return size == 1 ? b[m] : temp(a, b + size - m - 1, m + 1);  //直到数组长度为1,返回(返回小的)
		}
		else
		{
			return size == 1 ? a[m] : temp(a + size - m - 1, b, m + 1); //同上述
		}
		
	
}
int main()
{
	string row1;
	string row2;
	string row3;

	fstream f("D://算法分析与设计/input.txt");//从input.txt文件中读取三行
	getline(f, row1);
	getline(f, row2);
	getline(f, row3);

	int size = stoi(row1); //获取尺寸

	int* a = new int[size];
	int* b = new int[size];
	string r1;
	string r2;
	istringstream is1(row2);
	istringstream is2(row3);
	int i = 0;
	while (is1>>r1)     //更据空格符进行划分,赋值到a与b中
	{
		a[i] = stoi(r1);
		i++;
	}
	i = 0;
	while (is2>>r2)
	{
		b[i] = stoi(r2);
		i++;
	}
	f.close();
	int median = temp(a, b, size);

	ofstream of("D://算法分析与设计/output.txt"); //写入output.txt文件。 
	of << median << endl;
	of.close();
	cout << median;

}
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丁拾陆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值