See More

package algorithm.sorting; /** * The type Merge sort. */ public class MergeSort { /** * The Obj. */ static Helper obj = new Helper(); /** * Merge sort. * * @param arr the arr * @param leftIndex the left index * @param rightIndex the right index */ public static void mergeSort(int[] arr, int leftIndex, int rightIndex){ if (leftIndex < 0 || rightIndex < 0) return; if (rightIndex > leftIndex) { // Equivalent to (leftIndex+rightIndex)/2, but avoids overflow int mid = leftIndex + (rightIndex - leftIndex) / 2; // Sorting the first and second halves of the array mergeSort(arr, leftIndex, mid); mergeSort(arr, mid + 1, rightIndex); // Merging the array merge(arr, leftIndex, mid, rightIndex); } } /** * Merge. * * @param arr the arr * @param left the left * @param mid the mid * @param right the right */ public static void merge(int arr[], int left, int mid, int right) { int i,j,k; int sizeLeft = mid - left + 1; int sizeRight = right - mid; // Initializing temporary arrays int leftArr[] = new int[sizeLeft]; int rightArr[] = new int[sizeRight]; for( i=0;i