Can Someone help me understand this code (sorting)?

Hi all,

I had a test yesterday. Overall, I got everything correct, except for this one function. The exact instructions are below, as well as the correct code from the professor. Obviously, the requirements of the function could have probably been fulfilled with any kind of sorting algorithm...And I tried to write a bubble sort, but just couldn't quite remember it exactly.

Thanks.

void merge( double combo[], const double a[], unsigned aEls, const double b[], unsigned bEls );

aEls is the number of elements in array a, bEls is the number of elements in array b, and aEls+bEls is the number of elements in array combo.
merge may assume without checking that the elements of a are in increasing order and that the elements of b are in increasing order. When merge is called, combo is full of garbage.
merge's job is to fill combo with the elements from a and b so that the elements of combo are in increasing order.
For example if a were {2, 3, 5} and b were {4, 5, 10, 20}, then merge would set the 7 elements of combo to {2, 3, 4, 5, 5, 10, 20}.


1
2
3
4
5
6
void merge( double combo[], const double a[], unsigned aEls, 
                            const double b[], unsigned bEls
){
    for(  unsigned ai = 0, bi = 0, ci = 0;  ci < aEls+bEls;  )
        combo[ci++] = bi==bEls || ai<aEls && a[ai]<b[bi] ? a[ai++] : b[bi++];
}
You've got two decks of cards with the face up.
At each step you take the card with the lower value and put it in another pile.


Perhaps the use of the ternary operator is confusing you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void merge(/**/){
//there are two decks
   while( ai<aEls and bi<bEls )
      if( a[ai] < b[bi] )  //take the one with the lower value
         combo[ci++] = a[ai++];
      else
         combo[ci++] = b[bi++];

//one deck is empty, so we simply take the other deck
   while( ai<aEls ) 
      combo[ci++] = a[ai++];

   while( bi<bEls ) 
      combo[ci++] = b[bi++];
}
Last edited on
Topic archived. No new replies allowed.