I am having trouble undestanding this code, can someone please help. I dont understand what the for loops do also.

void Merge( long array[], long left, long middle, long right )

  long i, j;

  long temp[MAX_ARRAY_SIZE];

  for( i = middle + 1; i > left; i-- )

    temp[i - 1] = array[i - 1];

  for( j = middle; j < right; j++ )

    temp[right + middle - j] = array[j + 1];

  for( long k = left; k <= right; k++ )

    if( temp[j] < temp[i] )

      array[k] = temp[j--];


      array[k] = temp[i++];

11 Years
Discussion Span
Last Post by Ghost

When you don't understand an algorithm, the best way to figure it out is to run it through a debugger step by step, or write down the execution on paper. Of course, if the algorithm is wrong, or the right way to call the function is misunderstood, naturally it will be confusing. :) How is this Merge supposed to be called? Because if left is the first element in the array and right is the last, the algorithm is wrong because it accesses both temp and array out of bounds.


here's how a for statement works:

for ( int x = 0 ; x < 23 ; x++ ) 

the first part of the for loop, int x = 0, declares a variable. You can declare the veriable you'll use for the loop their.

the second part of the loop, x < 23, tells the compiler to keep repeating the code in the "LOOPED CODE" part until x < 23 is no longer true.

the third part of the loop, x++, tells the compiler to increment x every time the loop loops once. Basically, the code in the "LOOPED CODE" section above will repeat 23 times.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.