### A simplified Merge Sort Algorithm

• A simplified merge sort algorithm

• Consider the following sort algorithm:

 ``` Sort an array a[ ] of number: 1. split the first half of a[ ] to an array called "left[ ]" 2. split the second half of a[ ] to an array called "right[ ]" 3. Sort both halves of the arrays left[ ] and right[ ] 4. Merge the sorted array into the final result ```

• Example:

 ``` Sort: [6.4, 3.5, 7.5, 2.5, 8.9, 4.2, 9.2, 1.1] / \ / split into 2 halves \ / \ [6.4, 3.5, 7.5, 2.5] [8.9, 4.2, 9.2, 1.1] | | | Sort each half | (E.g.: use BubbleSort) V V [2.5, 3.5, 6.4, 7.5] [1.1, 4.2, 8.9, 9.2] \ / \ Merge sorted halves / \ / [1.1, 2.5, 3.5, 4.2, 6.4, 7.5, 8.9, 9.2] ```

• Code in Java:

 ``` public static void sort(double[] a) { double[] left, right; if ( a.length == 1 ) { // No need to sort ! return; } /* ================================================================= Split a[0 ..... middle-1 middle .... a.length-1] / \ left[0 .. middle-1] right[0 ... a.length-1-middle] ================================================================= */ int middle = a.length/2; left = new double[middle]; // Create array to hold left half for ( int i = 0; i < middle; i++ ) left[i] = a[i]; right = new double[a.length-middle]; // Create array to hold right half for ( int i = 0; i < a.length-middle; i++ ) right[i] = a[i+middle]; /* ====================================== Sort both halves of the arrays Let's use BubbleSort.... ====================================== */ BubbleSort.sort( left ); BubbleSort.sort( right ); /* ====================================== Merge both sorted arrays back ====================================== */ merge( a, left, right ); // We have discussed the Merge alg. already... } ```

Sample output:

 ```Sort: [6.4, 3.5, 7.5, 2.5, 8.9, 4.2, 9.2, 1.1] Split: [6.4, 3.5, 7.5, 2.5] | [8.9, 4.2, 9.2, 1.1] Sorted Left half: [2.5, 3.5, 6.4, 7.5] Sorted Right half: [1.1, 4.2, 8.9, 9.2] Result: [1.1, 2.5, 3.5, 4.2, 6.4, 7.5, 8.9, 9.2] ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   javac testProg1.java To run:          java testProg1

• Flash of brilliance....

• Wait...

 Why do we need to use Bubble Sort to sort the 2 halves of the array ??? We can use Merge Sort !!!