算法分析与设计实验-中位数问题
分治法解决中位数问题实验
问题描述
设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;
}
本文作者:发呆鱼
本文链接:https://www.cnblogs.com/dyiblog/articles/15929742.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步