Here you can find the source of merge(int[] a, int[] temp, int fromIndex, int toIndex)
Parameter | Description |
---|---|
a | array to subsort using this algorithm. |
temp | A temporary array to aid in the recursive merge process. |
fromIndex | The index to begin sorting in a . |
toIndex | The index to stop sorting in a . |
private static void merge(int[] a, int[] temp, int fromIndex, int toIndex)
//package com.java2s; //License from project: Open Source License public class Main { /**//from w w w . j a va 2 s .co m * Helper method for {@link #mergeSort(int[])}. Sorts the elements * between the indeces {@code fromIndex} and {@code toIndex} in the given * {@code a} array. * * @param a array to subsort using this algorithm. * @param temp A temporary array to aid in the recursive merge process. * @param fromIndex The index to begin sorting in {@code a}. * @param toIndex The index to stop sorting in {@code a}. * @see #mergeSort(int[]) * @see #finishMerge(int[], int, int, int, int[]) */ private static void merge(int[] a, int[] temp, int fromIndex, int toIndex) { if (fromIndex < toIndex) { int middleIndex = (fromIndex + toIndex) / 2; merge(a, temp, fromIndex, middleIndex); merge(a, temp, middleIndex + 1, toIndex); finishMerge(a, temp, fromIndex, middleIndex, toIndex); } } /** * Merges two adjacent array parts, each of which has been already sorted in * ascending order. * * @param a The array to sort using this algorithm. * @param temp A temporary array to aid in the recursive merge process. * @param fromIndex The index to begin sorting in {@code a}. * @param middleIndex The ending index of {@code a} of this part of the * merge process. * @param toIndex The index to stop sorting in {@code a}. * @see #mergeSort(int[]) * @see #merge(int[], int, int, int[]) */ private static void finishMerge(int a[], int[] temp, int fromIndex, int middleIndex, int toIndex) { int i = fromIndex; int j = middleIndex + 1; int k = fromIndex; while (i <= middleIndex && j <= toIndex) { if (a[i] < a[j]) { temp[k] = a[i]; i++; } else { temp[k] = a[j]; j++; } k++; } while (i <= middleIndex) { temp[k] = a[i]; i++; k++; } while (j <= toIndex) { temp[k] = a[j]; j++; k++; } for (k = fromIndex; k <= toIndex; k++) { // Fill and finish a[]int. a[k] = temp[k]; } } }