线性表之有序表(二路归并)
二路归并的有趣算法分别用顺序表和单链表的两种实现方式
1.求解中位数
2./*采用顺序表存放有序表,二路归并算法
void UnionList(SqList LA,SqList LB,SqList &LC)
{
int i = 0;//i,j分别为LA,LB的小标
int j = o;
int k = 0;//k为LC中元素个数
LC = (SqList)malloc(sizeof(SqList));//建立有序顺序表LC
while(i
{
if(LA->data[i]
{
LC->data[k] = LA->data[i];
i++;
k++;
}else{//LA->data[i]>LB->data[j]
LC->data[k]= LB->data[j];
j++;
k++;
}
while(i
{
LC->data[k] = LA->data[i]
i++;
k++;
}
whlie(j
{
LC->data[k] = LB->data[j];
j++;
k++;
}
LC->length = k;
}
//本算法的时间复杂度和空间复杂度都为O(m+n);
3.//采用单链表存放有序表,二路归并算法如下
void UnionList(LinkList LA,LinkList LB,LinkList &LC)
{
LinkList pa = LA->next,pb = LB->next,r,s;
LC = (LinkList)malloc(sizeof(LinkList));//创建LC的头节点
r = LC;//r始终指向LC的尾节点
while(pa!=NULL&&pb!=NULL)
{
if(pa->data
{
s=(LinkList
s->data = pa->data;
r->next = s;
r = s; //r始终指向尾节点
pa = pa->next;
}
else
{
s = (LinkList)malloc(sizeof(LinkList));
s->data = pb->data;
r->next = s;
r = s;
pb = pb->next;
}
}
while(pa!=NULL)
{
s = (LinkList)malloc(sizeof(LinkList));//复制节点
s->data = pa->data;
r->next = s;//尾插法将s插入到LC
r = s;
pa = pa->next;
}
whlie(pb!=NULL)
{
s = (LinkList)malloc(sizeof(LinkList));
s->data = pb->data;
r->next = s;
r = s;
pb = pb->next;
}
r->next = NULL;//尾节点的next置为空
}