#include "qsorter.h"

QSorter scpqsort;

void quick_sort_columns(SCPView* v, qs_comp_func compare,void* miscData) {

    scpqsort.comparator=compare;
    scpqsort.view=v;
    scpqsort.miscData=miscData;

    /*Start recursion*/
    qs_columns(0,v->columns-1);
}

void quick_sort_rows(SCPView* v, qs_comp_func compare,void* miscData) {

    scpqsort.comparator=compare;
    scpqsort.view=v;
    scpqsort.miscData=miscData;

    /*Start recursion*/
    qs_rows(0,v->rows-1);

}

void qs_columns(int l,int r) {

    int i=l;
    int j=r;

    /*Pivot index*/
    int x=(l+r)/2;

    do {
        while(scpqsort.comparator(scpqsort.view,i,x,scpqsort.miscData)<0) i++;
        while(scpqsort.comparator(scpqsort.view,x,j,scpqsort.miscData)<0) j--;

        if (i<=j) {
            scp_view_swap_columns(scpqsort.view,i,j);
            i++;
            j--;
        }

    }
    while(i<=j);

    if (l<j) qs_columns(l,j);
    if (i<r) qs_columns(i,r);
}

void qs_rows(int l,int r) {
    
    int i=l;
    int j=r;

    /*Pivot index*/
    int x=(l+r)/2;

    do {
        while(scpqsort.comparator(scpqsort.view,i,x,scpqsort.miscData)<0) i++;
        while(scpqsort.comparator(scpqsort.view,x,j,scpqsort.miscData)<0) j--;

        if (i<=j) {
            scp_view_swap_rows(scpqsort.view,i,j);
            i++;
            j--;
        }

    }
    while(i<=j);

    if (l<j) qs_rows(l,j);
    if (i<r) qs_rows(i,r);
}

