#include <stdio.h>
#define MaxSize 50//定义线性表的最大长度
typedef int ElemType;
typedef struct SqList {
ElemType data[MaxSize];
int length;
}SqList;
bool Merger(SqList& L1, SqList& L2,SqList &L3) {
int i = 0, j = 0,k=0;
while (i<L1.length&&j<L2.length)
{
if (L1.data[i] < L2.data[j]) {
L3.data[k] = L1.data[i];
k++;
i++;
}
else
{
L3.data[k] = L2.data[j];
k++;
j++;
}
}
while (i<L1.length)
{
L3.data[k++] = L1.data[i++];
}while (j<L2.length)
{
L3.data[k++] = L2.data[j++];
}
L3.length = k;
return true;
}
int main() {
SqList L1,L2,L3;
L1.length =0;
L2.length = 0;
L3.length = 0;
printf("请输入顺序表L1:");
for (int i = 0; i < 6; i++)
{
printf("请输入第%d个数:", i + 1);
scanf_s("%d", &L1.data[i]);
L1.length++;
}
printf("请输入顺序表L2:");
for (int i = 0; i < 8; i++)
{
printf("请输入第%d个数:", i + 1);
scanf_s("%d", &L2.data[i]);
L2.length++;
}
Merger(L1, L2,L3);
for (int i = 0; i < L3.length; i++)
{
printf("经过合并后L3的第%d个元素为%d\n", i + 1, L3.data[i]);
}
}
运行结果如下图所示:
算法思想:此题与之前顺序表逆置相似,本题需将两个线性表分别逆置一次,再将合并后的顺序表逆置一次即可,详细代码请看上节顺序表逆置即可。
附王道代码答案
详细代码实现如下:
算法思想:最少时间查找顺序表用折半查找思路找到元素X
自己的代码,这段代码逻辑有问题
#include <stdio.h>
#define MaxSize 50//定义线性表的最大长度
typedef int ElemType;
typedef struct SqList {
ElemType data[MaxSize];
int length;
}SqList;
void Search_X(SqList& L,ElemType n,ElemType x,int &mid) {
int low = 0, high = n;
while (low <= high)
{
mid= (low + high) / 2;
if (L.data[mid] > x) {
high = mid - 1;
}
else if (L.data[mid] < x)
{
low = mid + 1;
}
else
{
break;
}
}
if (low > high) {
for (int i = n - 1; i > high; i--) {
L.data[i + 1] = L.data[i];
}
mid = low; // 在循环结束后将插入位置赋值给 min
L.data[low] = x; // 将元素插入到 low 的位置
L.length++; // 更新顺序表的长度
}
}
void exchange(SqList& L, ElemType mid) {
int temp;
temp = L.data[mid];
L.data[mid] = L.data[mid + 1];
L.data[mid + 1] = temp;
}
int main() {
SqList L;
L.length = 0;
int x, n,mid;
printf("请输入要建立顺序表的大小n:");
scanf_s("%d", &n);
printf("请输入顺序表L:");
for (int i = 0; i < n; i++)
{
printf("请输入第%d个数:", i + 1);
scanf_s("%d", &L.data[i]);
L.length++;
}
printf("请输入要找的X的值:");
scanf_s("%d", &x);
Search_X(L, x, n, mid);
if (L.data[mid] == x && mid != n - 1) {
printf("找到的X值的位置在%d", mid+1);
exchange(L, mid);
}
for (int i = 0; i < L.length; i++)
{
printf("经过改变后L的第%d个元素为%d\n", i + 1, L.data[i]);
}
}