當前位置:編程學習大全網 - 編程語言 - C語言編程:編寫程序將兩個有序數組A、B合並成另壹個有序的數組C,設為升序。

C語言編程:編寫程序將兩個有序數組A、B合並成另壹個有序的數組C,設為升序。

#include<stdio.h>

voidmain()

{

inta[10],b[10],c[20],i,ia,ib,ic;

printf("pleaseinputthefirstarray\n");

for(i=0;i<10;i++)

scanf("%d",&a[i]);

for(i=0;i<10;i++)

scanf("%d",&b[i]);

printf("\n");

ia=0;ib=0;ic=0;

while(ia<10&&ib<10)

{

if(a[ia]<b[ib])

{

c[ic]=a[ia];

ia++;

}

else{

c[ic]=b[ib];

ib++;

}

ic++;

}

while(ia<10)

{

c[ic]=a[ia];

ia++;

ic++;

}

while(ib<10)

{

c[ic]=b[ib];

ib++;

ic++;

}

for(i=0;i<20;i++)

{

printf("%5d",c[i]);}

}

擴展資料

C語言歸並排序

#include<stdio.h>

#defineLEN8

inta[LEN]={5,2,4,7,1,3,2,6};

inttempa[LEN];

voidmerge(inta[],inttempa[],intleft,intright,intrightend)

{

inti,temp;

intleftend=right-1;

intnum=rightend-left+1;

temp=left;

while(left<=leftend&&right<=rightend)

{

if(a[left]<a[right])

{

tempa[temp++]=a[left++];

}

else

{

tempa[temp++]=a[right++];

}

}

while(left<=leftend)

{

tempa[temp++]=a[left++];

}

while(right<=rightend)

{

tempa[temp++]=a[right++];

}

for(i=0;i<num;i++,rightend--)

{

a[rightend]=tempa[rightend];

}

}

voidsort(inta[],inttempa[],intleft,intright)

{

intmid;

if(left<right)

{

mid=(left+right)/2;

sort(a,tempa,left,mid);

sort(a,tempa,mid+1,right);

merge(a,tempa,left,mid+1,right);

}

}

intmain()

{

sort(a,tempa,0,7);

for(inti=0;i<LEN;++i)

{

printf("%d,",a[i]);

}

return0;

}

  • 上一篇:軟件開發工程師是什麽?
  • 下一篇:有沒有什麽關於怪獸給人類帶來災難或者死亡的神話傳說?他們的英文名是什麽?就像啟示錄中的四騎士
  • copyright 2024編程學習大全網