兩個排序數(shù)組合并 如何將兩個有序數(shù)組合并到一個有序數(shù)組中?
如何將兩個有序數(shù)組合并到一個有序數(shù)組中?這很簡單:代碼如下(此處不考慮Object,假設(shè)為int[]):publicint[]getNewArrays(int[]one,int[]two){intle
如何將兩個有序數(shù)組合并到一個有序數(shù)組中?
這很簡單:代碼如下(此處不考慮Object,假設(shè)為int[]):publicint[]getNewArrays(int[]one,int[]two){intlen=one.lengthintlen2=two.lengthintlen3=oneLength twoLength//得到兩數(shù)組長度和int[]newArray=newint[len3]//創(chuàng)建第三個數(shù)組,長度=兩數(shù)組長度之和for(inti=0i<len3i ){if(i<len){//如果i<len,則賦值為one中的元素newArray[i]=one[i]continue}intt=i-len//t從0開始newArray[i]=two[t]//后面的元素賦值為two中的元素}//對第三個數(shù)組一一賦值,值為前兩個數(shù)組Arrays.sort(newArray)//對第三個數(shù)組排序此處使用的是java自帶的sort方法//也可使用冒泡排序,此處不演示returnnewArray}完
如何用C語言編程將兩個有序數(shù)組a,b合并成一個數(shù)組c?
基本思想:
1)先在A、B數(shù)組中各取第一個元素進(jìn)行比較,將小的元素放入C數(shù)組;
2)取小的元素所在數(shù)組的下一個元素與另一數(shù)組中上次比較后較大的元素比較,重復(fù)上述比較過程,直到某個數(shù)組被先排完;
3)將另一個數(shù)組剩余元素抄入C數(shù)組,合并排序完成。
#include
void main()
{
int
a[10],b[10],c[20],i,ia,ib,ic
printf("please input the first arrayn")
for(i=0i
scanf("%d",&a[i])
for(i=0i
scanf("%d",&b[i])
printf("n")
ia=0ib=0ic=0
while(ia
{
if(a[ia]
{
c[ic]=a[ia]
ia
}
else{
c[ic]=b[ib]
ib
}
ic
}
while(ia
{
c[ic]=a[ia]
ia
ic
}
while(ib
{
c[ic]=b[ib]
ib
ic
}
for(i=0i
{
printf("]",c[i])}
}
如何將兩個數(shù)組先合并然后再進(jìn)行排序?
這里是借用第三個數(shù)組。原理:先將兩個數(shù)組復(fù)制到第三個數(shù)組中,然后對第三個數(shù)組排序如果不使用第三個函數(shù),那么下面這個函數(shù)一樣可以做到,不過函數(shù)聲明就要改成:char* fun(char *dest, char *str, char *dest) /*------------------------------函數(shù)--------------------------------*/char* fun(char *str1,char *str2,char *dest) //前提,目標(biāo)數(shù)組能偶容納兩個數(shù)組{ char *tmp=dest char *tmp_dest=dest if(!dest) return NULL while(*str1) //將str1復(fù)制進(jìn)dest *tmp =*str1 while(*str2) //將str2復(fù)制進(jìn)dest *tmp =*str2 tmp_dest-- // while(* tmp_dest) //選擇排序法 { char *tmp_px=NULL tmp=tmp_dest while(* tmp) //找到后面一串的最值 { if(*tmp_dest<*tmp) tmp_px=tmp } if(!tmp_px) { char ch=*tmp_dest *tmp_dest=*tmp_px *tmp_px=ch } } return dest}