|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 beannaeb 于 2020-9-26 21:48 编辑
有两个递增有序顺序表A和B,分别含有n和m个整数元素(最大的元素不超过32767),假设这n+m个元素均不相同.设计一个算法求n+m个元素中第k小的元素.如果参数k错误,算法返回0,否则算法返回1,并且用参数e表示求出的第k小的元素.
本帖最后由 sunrise085 于 2020-9-26 22:40 编辑
你的程序没什么大问题,就是93行写的不对。函数调用怎么这么写?printf中两个格式化字符,但是后面只给了一个变量k
- #include<stdio.h>
- #define MaxSize 100
- typedef int ElemType;
- typedef struct
- {
- ElemType data[MaxSize];
- int length;
- }SqList;
- void InitList(SqList &L)
- {
- L.length=0;
- }
- int GetElem(SqList L,int i,ElemType &e)
- {
- if(i<1||i>L.length)
- return 0;
- else
- {
- e=L.data[i-1];
- return 1;
- }
- }
- int InsElem(SqList&L,ElemType x,int i)
- {
- int j;
- if(i<1||i>L.length+1)
- return 0;
- for (j=L.length;j>i;j--)
- L.data[j]=L.data[j-1];
- L.data[i-1]=x;
- L.length++;
- return 1;
- }
- void DispList(SqList L)
- {
- int i;
- for (i=0;i<L.length;i++)
- printf("%d ",L.data[i]);
- printf("\n");
- }
- #define INF 32767
- int Topk2(SqList A,SqList B,int k,ElemType&e)
- {
- int i=0,j=0;
- if(k<1||k>A.length+B.length)
- return 0;
- while(true)
- {
- k--;
- int x=(i<A.length?A.data[i]:INF);
- int y=(j<B.length?B.data[j]:INF);
- if(x<y)
- {
- if(k==0)
- {
- e=x;
- return 1;
- }
- i++;
- }
- else
- {
- if(k==0)
- {
- e=y;
- return 1;
- }
- j++;
- }
- }
- }
- int main()
- {
- int k=2,flag;
- ElemType e;
- SqList A;
- SqList B;
- InitList(A);
- InitList(B);
- InsElem(A,1,1);
- InsElem(A,2,2);
- InsElem(A,3,3);
- InsElem(A,4,4);
- InsElem(A,5,5);
- InsElem(A,6,6);
- InsElem(B,7,1);
- InsElem(B,8,2);
- InsElem(B,9,3);
- InsElem(B,10,4);
- InsElem(B,11,5);
- InsElem(B,12,6);
- printf("线性表A:");
- DispList(A);
- printf("线性表B:");
- DispList(B);
- flag=Topk2(A,B,k,e);//调用函数Topk2,得到元素e,若flag为0,说明k参数不对,没找到。
- if (flag)
- printf("第%d小元素为:%d\n",k,e);
- else
- printf("参数k设置错误,k小于1或者超出两个列表的长度总和!");
- }
复制代码
|
|