I haven't compiled and tested the following code, but I am reasonably confident. I am assuming both input arrays are already sorted. There is more work to do to make this general purpose as opposed to a solution for this example only. No doubt the two phases I identify could be combined, but perhaps that would be harder to read and verify;
void merge_example()
{
int a[] = {1,2,4,6};
int b[] = {3,5,7};
int c[100]; // fixme - production code would need a robust way
// to ensure c[] always big enough
int nbr_a = sizeof(a)/sizeof(a[0]);
int nbr_b = sizeof(b)/sizeof(b[0]);
int i=0, j=0, k=0;
// Phase 1) 2 input arrays not exhausted
while( i<nbr_a && j<nbr_b )
{
if( a[i] <= b[j] )
c[k++] = a[i++];
else
c[k++] = b[j++];
}
// Phase 2) 1 input array not exhausted
while( i < nbr_a )
c[k++] = a[i++];
while( j < nbr_b )
c[k++] = b[j++];
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…