c語言合并兩個(gè)有序數(shù)組 兩個(gè)數(shù)組合并C語言?
兩個(gè)數(shù)組合并C語言?int main(){char a[]=“123456”char b[]=“abcde”int buflen=strlen(a)strlen(b)char*p=(char*)mal
兩個(gè)數(shù)組合并C語言?
int main(){char a[]=“123456”char b[]=“abcde”int buflen=strlen(a)strlen(b)char*p=(char*)malloc(buflen 1)memset(p,0,buflen)printf(%dn”,buflen)strcpy(p,a)strcat(p,b)printf(%sn”,p)free(p)}C的數(shù)組在創(chuàng)建后不能更改,因此數(shù)組合并的思想是將數(shù)組放入足夠大的空間來形成一個(gè)新的陣列。上面的函數(shù)是一個(gè)比較簡單的合并方法
這里是借用第三個(gè)數(shù)組。
原理:先將兩個(gè)數(shù)組復(fù)制到第三個(gè)數(shù)組,然后對第三個(gè)數(shù)組排序
如果第三個(gè)函數(shù)沒有使用,下面的函數(shù)也可以這樣做,但是函數(shù)聲明應(yīng)該改為:
char*fun(char*DeST,char*STR,char*dest)]/*----函數(shù)----------*/
char*fun(char*dest)*STR1,char*STR2,char*dest)//如果目標(biāo)數(shù)組能容納兩個(gè)數(shù)組
{
char*TMP=dest
char*TMPuudest=dest
如果(!Dest)
return null
while(*STR1)//將STR1復(fù)制到Dest
*TMP=*STR1
while(*STR2)//將STR2復(fù)制到Dest
*TMP=*STR2
TMPudest--//
while(*TMPudest)//選擇排序方法
{
char TMPupx=null
TMP=TMPudest
while(*TMP)//查找下列值的最大值字符串
{
如果(*TMP)udest
TMPupx=TMP
}
如果(!tmpupx)
{
char ch=*tmpudest
*tmpudest=*tmpupx
*tmpupx=ch
}
}
返回dest
}