public void sort(int[] a) { mergeSort(a, 0, a.length - 1); } // Use merge sort to sort the array between indexes left // and right. Split the list in half, recursively // sort each half, and then merge the sorted halves // back together. private void mergeSort(int[] a, int left, int right) { if (left < right) { // Find the mid point. Sort the first half and second // half separately. int middle = (left + right) / 2; mergeSort(a, left, middle); mergeSort(a, middle + 1, right); // Merge the sorted arrays together to form one sorted array. merge(a, left, middle, right); } // Merge the sorted lists a[left]..a[middle] and // a[middle+1]..a[right] into one large sorted list // of a[left]..a[right]. private void merge(int[] a, int left, int middle, int right) { // copy data into temp array int[] temp = new int[a.length]; for (int i = left; i <= right; i++) { temp[i] = a[i]; } int indexLeft = left; int indexRight = middle + 1; int endLeft = middle; int endRight = right; for (int target = left; target <= endRight; target++) { if (indexLeft > endLeft) { // Used up all the elements in left portion a[target] = temp[indexRight]; indexRight++; } else if (indexRight > endRight) { // Used up all the elements in right portion a[target] = temp[indexLeft]; indexLeft++; } else if (temp[indexLeft] < temp[indexRight]) { // Left value is less. Use it. a[target] = temp[indexLeft]; indexLeft++; } else { // Right value is less. Use it. a[target] = temp[indexRight]; indexRight++; } } }