顺序表的插入和删除算法的时间复杂度为O(n);
求顺序表表长以及取顺序表第i个元素的值这两个算法的时间复杂度为O(1)
查找算法LocateElem_Sq的时间复杂度为O(L.length)
查找算法的实现:
int LocateElem(SqList &L,ElemType elem,status(*compare)(ElemType&,ElemType &))
{
for(int index=1;index<=L.length;++index){
if(compare(elem,L.elem[index-1]))
return index;
}
return 0;
}
int LocateElem(SqList &L,ElemType elem,Status(*compare)(ElemType&,ElemType&))
{
int index=1;
ElemType *p=L.elem;
while(index<=L.length&&!(compare(elem,*p++)))
++index;
if(index<=L.length)
return index;
return 0;
}
顺序表的合并操作://过多代码冗余(顺序表的缺点在于长度固定,添加元素要考虑是否溢出的情况)
void MergeList(SqList &La,SqList &Lb,SqList &Lc)
{
InitList(Lc);
int i=j=k=1;
for(i<=La.length&&j<=Lb.length){
if(La.elem[i]<=Lb.elem[j]){
Lc.elem[k++]=La.elem[i++];
++Lc.length;
}
else{
Lc.elem[k++]=Lb.elem[j++];
++Lc.length;
}
if(Lc.length>=Lc.listsize){
ElemType *newbase=(ElemType*)realloc(Lc.elem,(LISTINCREMENT+Lc.listsize)*sizeof(ElemType));
if(!newbase)
exit(OVERFLOW);
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
}
while(i<=La.length){
Lc.elem[k++]=La.elem[i++];
++Lc.length;
if(Lc.length>=Lc.listsize){
ElemType *newbase=(ElemType*)realloc(Lc.elem,(LISTINCREMENT+Lc.listsize)*sizeof(ElemType));
if(!newbase)
exit(OVERFLOW);
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
}
while(j<=Lb.length){
Lc.elem[k++]=La.elem[j++];
++Lc.length;
if(Lc.length>=Lc.listsize){
ElemType *newbase=(ElemType*)realloc(Lc.elem,(LISTINCREMENT+Lc.listsize)*sizeof(ElemType));
if(!newbase)
exit(OVERFLOW);
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
}
}
//改进:一次性分配“足够大”的空间给新顺序表
void MergeList_Sq(SqList &La,SqList &Lb,SqList Lc)
{
Lc.elem=(ElemType*)malloc((La.length+Lb.length)*sizeof(ElemType));
if(!Lc.elem)
exit(OVERFLOW);
Lc.listsize=La.length+Lb.length;
int i=j=k=1;
for(i<=La.length&&Lb.length){
if(La.elem[i]<=Lb.elem[i]){
Lc.elem[k++]=La.elem[i++];
++Lc.length;
}
else{
Lc.elem[k++]=Lb.elem[j++];
++Lc.length;
}
}
while(i<=La.length){
Lc.elem[k++]=La.elem[i++];
++Lc.length;
}
while(j<=Lb.length){
Lc.elem[k++]=Lb.elem[j++];
++Lc.length;
}
}
//使用线性表来表示集合,在其上面的做集合运算要先对线性表进行排序
顺序表查找算法
最新推荐文章于 2022-08-04 23:38:43 发布