一个长度为n(n≥1)的升序排列顺序表La,处在第n/2个位置的数称为La的中位数。
例如:若La=(11,13,17,15,19),则La的中位数是15。
两个升序排列的顺序表的中位数是含它们所有元素的升序序列的中位数。
例如,若Lb=(2,6,8,4,20),则La和Lb的中位数是11。
现有两个等长的升序排列的顺序表La和Lb,试
设计一个在时间和空间两方面都尽可能高效的算法,找出两个顺序表的中位数
#include <iostream>
#define ok 1
#define error 0
#define MaxSize 100
using namespace std;
typedef int status;
typedef int ElemType;
typedef struct
{
ElemType *elem;
int length = 0;
}SqList;
//函数声明
status InitList(SqList &L);
status CreateList(SqList &L , int n);
status DispList(SqList L);
void List_up(SqList &L);
void Union(SqList La, SqList Lb);
status Median(SqList &La, SqList Lb);
int mymiddle(SqList La, SqList Lb, int n);
int main()
{
int n, middle, mi ;
SqList L;
InitList(L);
SqList La;
InitList(La);
SqList Lb;
InitList(Lb);
cout << "线性表中元素的个数?" << endl;
cin >> n;
cout << "请输入La中的元素:" << endl;
CreateList(La, n);
cout << "请输入Lb中的元素:" << endl;
CreateList(Lb, n);
cout << "调整之后的La为:" << ' ' ;
List_up(La);
cout << endl;
cout << "调整之后的Lb为:" << ' ';
List_up(Lb);
cout << endl;
mymiddle( La, Lb, n);
}
//初始化
status InitList(SqList &L)
{
L.elem = new ElemType[MaxSize];
L.length = 0;
return ok;
}
//创建
int CreateList(SqList &L , int n)
{
for (int i = 0; i < n; i++)
cin >> L.elem[i];
L.length = n;
return 0;
}
//输出
status DispList(SqList L)
{
for (int i = 0; i < L.length; i++)
cout << L.elem[i] << ' ';
return ok;
}
//排序
void List_up(SqList &L)
{
for (int i = 1 ; i < L.length; i++)
{
for (int j = 0; j < L.length - 1; j++)
{
if (L.elem[j] > L.elem[j + 1])
{
int temp = L.elem[j];
L.elem[j] = L.elem[j + 1];
L.elem[j + 1] = temp;
}
}
}
for (int i = 0; i < L.length; i++)
cout << L.elem[i] << ' ';
}
int mymiddle(SqList La, SqList Lb, int n)
{ //n为两表长度的二分之一
ElemType e; //e是最后确定的中位数
int k = 0, i = 0, j = 0;
while (k < n)
{
if(La.elem[i] < Lb.elem[j]) //比较两个表中的元素,只需比较n/2次,把小的元素赋给e,即为中位数的值
{
e = La.elem[i];
n++;
}
else
{
e = Lb.elem[j];
j++;
}
k++;
}
cout << "两表合并之后的中位数为:\n";
cout << e;
return 0;
}
找出两个升序顺序表的中位数
最新推荐文章于 2023-01-02 14:23:21 发布