线性表-归并算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*例如:有两个线性表LA=(1,5,7,15)
                    LB=(3,6,8,9,13,15,17)
则:                LC=(1,3,6,8,9,13,15,15,17)
上述问题要求可知,LC中的数据元素或是LA中的数据元素,或是LB中的数据元素,则首先设LC为空表,然后将LA或LBs中的元素逐个插入到LC当中。
为使LC中元素按值非递减排列,可设两个指针i,j分别向LA和LB中的某个元素,若设i当所指的元素为a,j所指的元素为b则当前应插LC元素c为
 
    |->  b a>b
  c=|->  a a=b
    |->  a a<b
    显然,设指针i的j的初使值为1,在所指元素插入LC之后,指针在表LA或LB中将顺序后移。
*/
template<class T>
class merge<T>::
void MergetList(T La,T Lb, T Lc)
{
/*已知线性表La和Lb中的数据元素按值非递减排列*/
/*归并La和Lb得到新的线性表Lc,Lc的数据元素也按值非递减排列*/
    InitList(Lc);
    i=j=1;k=0;
    La_len=ListLength(La);
    Lb_len=ListLength(Lb);
    while((i<La_len)&&(j<=Lb_len))
    {
        GetElem(La,i,ai);
        GetElem(Lb,j,bj);
        if(ai<bj)
        {
            ListInsert(Lc,++k,ai);
            ++i;
        }
        else if (ai==bj)
        {
            ListInsert(Lc,++k,ai);++i;++j;
        }
        else
        {
            ListInsert(Lc,++k,bj);++i;++j;
        }
    }
    while(i<=La_len)
    {
        /*如果La没有取完,则将La中的所剩元素插入到表Lc中*/
        GetElem(La,i++,ai);
        ListInsert(Lc,++k,ai);
    }
    while(j<=Lb_len)
    {
        /*如果La没有取完,则将La中的所剩元素插入到表Lc中*/
        GetElem(La,j++,bj);
        ListInsert(Lc,++k,bj);
    }
}/***********************************************************************-*/
/* MergeList                                                             */
/************************************************************************/
上一篇:2019年5月下旬最值得一读的9本技术书籍(微服务架构、算法、大数据等书籍)!


下一篇:java自定义类加载器