/* Merge two sorted arrays */
#include <stdio.h>
#include <stdlib.h>

int *merge(int a[], int la, int b[], int lb);

void merge_rec(int a[], int la, int b[], int lb, int r[], int lr);

void print(int a[], int la);

int main(){
    int x[6] = { 1, 2, 4, 7, 12, 20 };
    int y[8] = { 2, 3, 6, 14, 15, 16, 18, 22 };
    int *r=NULL;

    print(x, 6);
    print(y, 8);

    r=merge(x, 6, y, 8);

    print(r, 6+8);
    return 0;
}

void print(int a[], int la){
    int i;
    for(i=0; i<la-1; i++)
        printf("%d, ", a[i]);
    printf("%d\n", a[la-1]);
}

int *merge(int a[], int la, int b[], int lb){
    int *r=malloc(sizeof(int)*(la+lb));
    printf("%s: %d\n", __FILE__, __LINE__);
    merge_rec(a,la,b,lb,r,la+lb);
    return r;
}


void merge_rec(int a[], int la, int b[], int lb, int r[], int lr){
    if (la==0 && lb==0) return; 
    if (la==0) {
        printf("%d: %d %d\n", __LINE__, lb, b[0]);
        r[0]=b[0];
        merge_rec(a,la,&b[1],lb-1,&r[1],lr-1);
        printf("%d: (%d) ", __LINE__, lr); print(r,lr);
    }
    else if (lb==0) {
        printf("%d: %d %d\n", __LINE__, la, a[0]);
        r[0]=a[0];
        merge_rec(&a[1],la-1,b,lb,&r[1],lr-1);
        printf("%d: (%d) ", __LINE__, lr); print(r,lr);
    }
    else {
        if(a[0]<=b[0]) {
            printf("%d: %d %d\n", __LINE__, la, a[0]);
            r[0]=a[0];
            merge_rec(&a[1],la-1,b,lb,&r[1],lr-1);
            printf("%d: (%d) ", __LINE__, lr); print(r,lr);
        }
        else {
            printf("%d: %d %d\n", __LINE__, lb, b[0]);
            r[0]=b[0];
            merge_rec(a,la,&b[1],lb-1,&r[1],lr-1);
            printf("%d: (%d) ", __LINE__, lr); print(r,lr);
        }
    }

}
