public class Sorter { public static void mergeSort(int[] a) { int[] temp = new int[a.length]; mergeSort(a, temp, 0, a.length - 1); } private static void mergeSort(int[] a, int[] temp, int left, int right) { if (left >= right) { // base case return; } // sort the two halves int mid = (left + right) / 2; mergeSort(a, temp, left, mid); mergeSort(a, temp, mid + 1, right); // merge the sorted halves into a sorted whole merge(a, temp, left, right); } private static void merge(int[] a, int[] temp, int left, int right) { int mid = (left + right) / 2; int count = right - left + 1; int l = left; // counter indexes for L, R int r = mid + 1; // main loop to copy the halves into the temp array for (int i = 0; i < count; i++) if (r > right) { // finished right; use left temp[i] = a[l++]; } else if (l > mid) { // finished left; use right temp[i] = a[r++]; } else if (a[l] < a[r]) { // left is smaller (better) temp[i] = a[l++]; } else { // right is smaller (better) temp[i] = a[r++]; } // copy sorted temp array back into main array for (int i = 0; i < count; i++) { a[left + i] = temp[i]; } } public static void quickSort(int[] a) { quickSort(a, 0, a.length - 1); } private static void quickSort(int[] a, int min, int max) { if (min >= max) { // base case; no need to sort return; } // choose pivot -- we'll use the first element (might be bad!) int pivot = a[min]; swap(a, min, max); // move pivot to end // partition the two sides of the array int middle = partition(a, min, max - 1, pivot); // restore the pivot to its proper location swap(a, middle, max); // recursively sort the left and right partitions quickSort(a, min, middle - 1); quickSort(a, middle + 1, max); } // partitions a with elements < pivot on left and // elements > pivot on right; // returns index of element that should be swapped with pivot private static int partition(int[] a, int i, int j, int pivot) { i--; j++; // kludge because the loops pre-increment while (true) { // move index markers i,j toward center // until we find a pair of mis-partitioned elements do { i++; } while (i < j && a[i] < pivot); do { j--; } while (i < j && a[j] > pivot); if (i >= j) { break; } else { swap(a, i, j); } } return i; } private static void swap(int[] nums, int i, int j) { if (i == j) { return; } int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }