Import java. util. Arrays;
Public class MergeSort {
Public static void main (String [] args ){
Int [] a = {20, 1, 3, 8, 5, 9, 4, 25 };
MergeSort (a, 0, a. length-1 );
System. out. println (Arrays. toString ());
}
Public static void mergeSort (int [] a, int first, int last ){
Int len = a. length;
If (first> = last) return;
If (first <last ){
// Int mid = (first + last)/2;
// To avoid overflow, you should do it like this:
Int mid = (first & last) + (first ^ last)> 1 );
Int [] temp = new int [len];
MergeSort (a, first, mid );
MergeSort (a, mid + 1, last );
MergeTwoArray (temp, a, first, mid, last );
}
}
Public static void mergeTwoArray (int [] temp, int [] a, int first, int mid, int last ){
Int I = first;
Int j = mid + 1;
Int k = 0;
While (I <= mid & j <= last ){
If (a [I] <a [j]) {
Temp [k] = a [I];
I ++;
} Else {
Temp [k] = a [j];
J ++;
}
K ++;
}
While (I <= mid ){
Temp [k ++] = a [I ++];
}
While (j <= last ){
Temp [k ++] = a [j ++];
}
// System. arraycopy (src, srcPos, dest, destPos, length );
// At first, I write it like this:
// System. arraycopy (temp, 0, a, 0, temp. length );
// I can't get it right until I do it like this:
System. arraycopy (temp, 0, a, first, last-first + 1 );
// System. arraycopy (temp, 0, a, first, k); // it also works
}
}
Author: gznicky