#include <iostream>
#include <vector>
using namespace std;
// merge left and right half of A into B, then assign all items in B into A
// left half range: [low, m], right half range: [m+1, high]
int merge(int A[], int low, int m, int high) { // note, there is a 'm' parameter denoting for middle index
int i = low, j = m+1, k = low;
int B[500]; // gist, temporary array
while(i <= m && j <= high) {
if(A[i] < A[j])
B[k++] = A[i++];
else
B[k++] = A[j++];
}
while(i <= m)
B[k++] = A[i++];
while(j <= high)
B[k++] = A[j++];
k--; // gist
for(int t=low; t<=high; t++)
A[t] = B[t];
}
void merge_sort(int A[], int low, int high) {
if(low >= high) return;
int m = (low + high) >> 1;
merge_sort(A, low, m);
merge_sort(A, m+1, high);
merge(A, low, m, high);
}
int main()
{
int A[] = {3,4,9,2,1};
merge_sort(A, 0, 4);
for(int i=0; i<5; i++) cout << A[i] << " ";
return 0;
}