MergeSort

   

    Problem and Approach

    The Algorithm(s)

void MergeSort( float array[], int start_pos, int end_pos)

{

    if ( start_pos == end_pos ) // Only one element

        return;

    int middle_pos = ( start_pos + end_pos ) / 2;       // Divide in half

    MergeSort( array, start_pos, middle_pos);          // Sort left half

    MergeSort( array, middle_pos + 1, end_pos);     // Sort right half

    Merge( array, start_pos, middle_pos, end_pos); // Merge together

           }

 

            void Merge( float array[], int start_pos, int middle_pos, int end_pos)

            {

                float copy_array[end_pos - start_pos + 1]; // Copy elements -- NOT STANDARD-COMPLIANT!

                for( int i = start_pos; i <= end_pos; i++)     // Will sort into parameter array

                    copy_array[ i - start_pos ] = array[i];

                int left = 0, right = middle_pos + 1 - start_pos;   // Keep track of where we are in each half

                int index = start_pos;    // Keep track of how much of sorted array has been filled in

                while ( left <= middle_pos - start_pos && right <= end_pos - start_pos )

                    {

                     if( copy_array[left] < copy_array[right] )  // Element in left is smaller; goes first

                        array[index++] = copy_array[left++];

                     else                                                          // Element in right is smaller; goes first

                        array[index++] = copy_array[right++];

                    }

                    // Out of loop; either left = middle_pos + 1 (sorted all left elements into array)

                    //  or right = end_pos + 1 (sorted all right elements into array).    

                    //  Now: copy remaining leftover elements from appropriate half into array.

                    // Only one of these loops will actually execute; the other will fail the first check

                    while ( right <= end_pos - start_pos )

                        array[index++] = copy_array[right++];

                    while ( left <= middle_pos - start_pos )

                        array[index++] = copy_array[left++];

                }

 

    Why does this work?

Correctness of MergeSort

Correctness of Merge

    Runtime Analysis

   

      A Word about Efficiency