Tuesday, February 28, 2012

Yet Another Code Snippet for Merge Sort (Java)


Conceptually, merge sort works as follows:
  1. Divide the unsorted list into two sublists of about half the size
  2. Sort each of the two sublists
  3. Merge the two sorted sublists back into one sorted list.
The algorithm was invented by John von Neumann in 1945.
The following code shows how to implement merge sort in Java.
    /**
     * Mergesort algorithm.
     @param a an array of Comparable items.
     */
    public static void mergeSortComparable [ ] ) {
        Comparable [ ] tmpArray = new Comparablea.length ];
        mergeSorta, tmpArray, 0, a.length - );
    }
    
    /**
     * Internal method that makes recursive calls.
     @param a an array of Comparable items.
     @param tmpArray an array to place the merged result.
     @param left the left-most index of the subarray.
     @param right the right-most index of the subarray.
     */
    private static void mergeSortComparable [ ] a, Comparable [ ] tmpArray,
            int left, int right ) {
        ifleft < right ) {
            int center = left + right 2;
            mergeSorta, tmpArray, left, center );
            mergeSorta, tmpArray, center + 1, right );
            mergea, tmpArray, left, center + 1, right );
        }
    }
    
    /**
     * Internal method that merges two sorted halves of a subarray.
     @param a an array of Comparable items.
     @param tmpArray an array to place the merged result.
     @param leftPos the left-most index of the subarray.
     @param rightPos the index of the start of the second half.
     @param rightEnd the right-most index of the subarray.
     */
    private static void mergeComparable [ ] a, Comparable [ ] tmpArray,
            int leftPos, int rightPos, int rightEnd ) {
        int leftEnd = rightPos - 1;
        int tmpPos = leftPos;
        int numElements = rightEnd - leftPos + 1;
        
        // Main loop
        whileleftPos <= leftEnd && rightPos <= rightEnd )
            ifaleftPos ].compareToarightPos ] ) <= )
                tmpArraytmpPos++ = aleftPos++ ];
            else
                tmpArraytmpPos++ = arightPos++ ];
        
        whileleftPos <= leftEnd )    // Copy rest of first half
            tmpArraytmpPos++ = aleftPos++ ];
        
        whilerightPos <= rightEnd )  // Copy rest of right half
            tmpArraytmpPos++ = arightPos++ ];
        
        // Copy tmpArray back
        forint i = 0; i < numElements; i++, rightEnd-- )
            arightEnd = tmpArrayrightEnd ];
    }

No comments:

Post a Comment