Picture from Wikipedia:
The upper part (red arraow) are drawen as a formal only. Only procedure calling
and local variables are generated during this pass. All is done by the "merge"
procedures, called on the end of each of "mergeSort" procedures before end.
Recursive variant of the described algorithm follows:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package merge1;
import java.util.ArrayList;
/**
*
* @author Student
*/
public class Merge1 {
public static void merge(int[] arr, int low, int mid, int high) {
ArrayList<Integer> temp = new ArrayList<Integer>();
int left = low;
int right = mid + 1;
//two halves> [low..mid]&[mid+1..high]
while (left <= mid && right <= high) {
if (arr[left] <= arr[right]) {
temp.add(arr[left]);
left++;
} else {
temp.add(arr[right]);
right++;
}
}
//copying the rest
while (left <= mid) {
temp.add(arr[left]);
left++;
}
while (right <= high) {
temp.add(arr[right]);
right++;
}
//copy to the original array
for (int i = low; i <= high; i++) {
arr[i] = temp.get(i - low);
}
}
public static void mergeSort(int[] arr, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);
merge(arr, low, mid, high);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int[] a = {12, 4, 9, 2, 18, 23, 11, 13, 5, 6, 10, 7};
mergeSort(a, 0, a.length-1);
for (int x : a) {
System.out.print(x + ", ");
}
}
}