/* Java class that has sort() method for sorting an array of int's, ** or a specified segment, thereof, into ascending order. ** Employs the classic recursive MergeSort algorithm. */ public class MergeSorterOfInt { private static int recDepth = -1; // remembers depth of recursion /* Rearranges the elements in the given array so that they are in ** ascending order. */ public static void sort(int[] a) { sort(a, 0, a.length); } /* Rearranges the elements in the given array segment (a[low..high)) ** so that they are in ascending order. */ public static void sort(int[] a, int low, int high) { //Next four lines are strictly for producing output that illustrates //the working of the algorithm. recDepth++; indent(recDepth); System.out.print("Before sorting:"); printArySeg(a, low, high); if (high - low < 2) { // segment length is less than two, so nothing need be done! } else { int mid = (low + high) / 2; sort(a, low, mid); //recursively sort 1st half of segment sort(a, mid, high); //recursively sort 2nd half of segment int[] b = merge(a, low, mid, a, mid, high); //merge sorted segments into a new array System.arraycopy(b, 0, a, low, b.length); //copy the new array into the segment } //Next four lines are strictly for producing output that illustrates //the working of the algorithm. indent(recDepth); System.out.print("After sorting:"); printArySeg(a, low, high); recDepth--; } /* Returns a new array containing the result of merging the elements ** in b[bLow,bHigh) and c[cLow,cHigh) into ascending order. */ public static int[] merge(int[] b, int bLow, int bHigh, int[] c, int cLow, int cHigh) { int[] result = new int[(bHigh-bLow) + (cHigh-cLow)]; int bPos = bLow, cPos = cLow; for (int k = 0; k != result.length; k++) { if (cPos == cHigh || (bPos != bHigh && b[bPos] <= c[cPos])) { result[k] = b[bPos]; bPos++; } else { result[k] = c[cPos]; cPos++; } } return result; } // methods for illustrating algorithm execution // -------------------------------------------- /* Prints the elements in the specified array segment, and then skips to ** next line. */ private static void printArySeg(int[] ary, int low, int high) { for (int i=low; i != high; i++) { System.out.print(ary[i] + " "); } System.out.println(); } // Prints "| " the specified number of times. private static void indent(int r) { for (int j=0; j != r; j++) { System.out.print("| "); } } // main() method for testing // ------------------------- public static void main(String[] args) { int[] junk = new int[] { 23, 12, 67, -4, 0,13, 19, 27, 5, 8, 15, -1, 0, 11, 4, 2, 13, 9, 5 }; sort(junk); //printArySeg(junk, 0, junk.length); } }