Tuesday, July 12, 2011

Mergesort in Java

private static void mergesort2(int[] arr, int[] helper, 
int left, int right)
    {
        if(left < right)
        {
            int center = (left + right)/2;
            mergesort2(arr, helper, left, center);
            mergesort2(arr, helper, center + 1, right);
            int rightPos = center + 1;
            int tmpPos = left;
            int i = left;
            while(left <= center || rightPos <= right)
            {
                if(left <= center && rightPos <= right)
                {
                    if(arr[left] < arr[rightPos])
                        helper[tmpPos] = arr[left++];
                    else
                        helper[tmpPos] = arr[rightPos++];
                }
                else if (left <= center)
                    helper[tmpPos] = arr[left++];
                else
                    helper[tmpPos] = arr[rightPos++];
                tmpPos++;
            }
            for(; i <= right; i++)
                arr[i] = helper[i];
            
        }
    }

No comments:

Post a Comment

There was an error in this gadget