实例四十四:两路归并排序
问题描述:
将两个有序字符串合并连接成另一有序字符串。
Combine two ordered strings into another ordered string.
算法思路:
将有序字符串 a 和 b 合并为有序字符串 c,我们先将 c 设置为空字符串,然后将 a 或 b 中的字符逐个插入到 c 中。
为了使 c 中字符有序,设两个指针 i 和 j 分别指向 a 和 b 中的第一个字符,然后比较两个指针所指字符,哪个指针所指字符小就将这个字符插入 c ,此指针后移,另一个指针不动,再继续比较,…;若其中一个字符串的字符元素都已经插入到 c 中,只需将另一字符串的剩余字符依次插入 c ,合并排序即完成。
To merge the ordered strings a and b into an ordered string c, we first set c to an empty string and then insert the characters in a or b into c one by one.
In order to make the characters in c order, set two pointers i and j to point to the first character in a and b respectively, and then compare the characters pointed by the two pointers. Which pointer refers to the small character and insert this character into c. After the pointer moves backward, the other pointer does not move, and then continue to compare, …; if the character elements of one of the strings have been inserted into c, simply insert the remaining characters of the other string into c, The merge sort is complete.
/*实例四十四:两路归并排序*/
#include<stdio.h>
#include<string.h>
int main()
{
char a[]="acehjlm";
char b[]="bdfgiknopq";
char c[80],*p;
int i=0,j=0,k=0;
while(a[i]!='\0'&&b[j]!='\0') //当字符串a和b都没有结束时
{
if(a[i]<b[j])
c[k]=a[i++];
else
c[k]=b[j++];
k++;
}
c[k]='\0';
if(a[i]=='\0') //取得没有结束的字符串剩余的所有字符
p=b+j;
else
p=a+i;
strcat(c,p);
puts(c);
return 0;
}
程序心得:
程序中使用一个指针变量 p ,p=a+i 是相对数组 a 的首地址的第 i 个偏移地址,可代表这个元素起始的一个字符串(p=a+j 类似)。
函数 strcat(c,p) 的功能是连接 c 与 p 两个字符,即将 p 字符串连接到 c 字符串。
The program uses a pointer variable p , p=a+i is the ith offset of the first address of the array a, which represents a string starting at the beginning of this element (p=a+j is similar).
The function of the function strcat(c,p) is to connect the two characters c and p, that is, connect the p string to the c string.
思考拓展:
1.两个整数序列合并的函数:(思考 for 和 while 循环的作用)
int merge(int a[],int n,int b[],int m,int *c)
{
int i,j;
for(i=j=0;i<n&&j<m;)
*c++=a[i]<b[i]?a[i++]:b[i++];
while(i<n)
*c++=a[i++];
while(j<m)
*c++=b[j++];
return 0;
}
2.下面是将两个升序链表 a 和 b 合并成一个升序链表的函数。( for 循环的特殊性,它的循环体为空,试思考其作用)
struct inNode
{ int num;
struct inNode *next;
};
inNode *merge(inNode *a,inNode *b)
{ inNode *h=a,*p*q;
while(b!=NULL)
{
for(p=h;p&&p->num<b->num;q=p;p=p->next);
if(p==h)
h=b;
else
q->next=b;
q=b;
b=b->next;
q->next=p;
}
return h;
}