/*AMS q-sort
	Author: Aaron M. Schinder
	Date: 4 May 2013
	Purpose: ams_qsort is an implementation of quicksort, the popular O(n*log(n)) sorting algorithm. There
	are millions of q-sort implementations out there, but this one is mine. This was programmed partially
	for the ability to sort multiple lists, but mostly for the exercise in converting a recursive program
	to a procedural loop.

	It has some desirable features over most implementations of qsort: 
		1. It doesn't use recursion of the function calls. Instead, it implements recursive behavior through
		the use of a tree data-structure. This means it won't blow your call-stack when sorting large lists
		(which is the point of having an O(n*log(n)) sorting algorithm in the first place!).
		2. What the actual sorting function returns is not a single sorted list, but a permutation map. The
		permutation map can be applied not just to this list, but to other related lists as well to sort
		each according to the first. First you acquire the permutation map that will sort the target list, 
		then you apply it to lists.

	Main functions of interest:
		bool quicksort(std::vector<T> *V, std::vector<long> *map, bool (*comparator)(T, T));
		bool rearrange(std::vector<T> *V, std::vector<long> *map);
		void invertmap(std::vector<long > *map, std::vector<long > *inv);
		void mapcompose(std::vector<long > *map_in_main, std::vector<long > *map_in_sub, long indstart);

	Typical use:
		quicksort(&myvector,&map,&comparatorfn);
		rearrange(&myvector,&map); //rearranges myvector (sorts it)
		rearrange(&myothervector, &map); //rearranges some other vector (sorts it according to myvector)

		invertmap(&map,&othermap); //creates a map which, when composed with map, de-permutes it.
		rearrange(&myothervector,&othermap); //unsorts the myothervector

		bool comparator(T A,T B)
		comparator is a pointer to a bool function that returns true if A>B, according to whatever evaluation of A and B you want.

*/

/*
Copyright (C) 2013 Aaron M. Schinder

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <stdlib.h>
#include <math.h>
#include <vector>
#include "ams_qsort.hpp"

using namespace std;

namespace ams_qsort
{

/*
function quicksort('array')
    if length('array') ≤ 1
        return 'array'  // an array of zero or one elements is already sorted
    select and remove a pivot value 'pivot' from 'array'
    create empty lists 'less' and 'greater'
    for each 'x' in 'array'
        if 'x' ≤ 'pivot' then append 'x' to 'less'
        else append 'x' to 'greater'
    return concatenate(quicksort('less'), 'pivot', quicksort('greater')) // two recursive calls
*/



//returns random double from 0 to 1
double intl_randd()
{
	return ((double) rand())/((double) RAND_MAX);
}

//returns a random long integer between I and J
long intl_randlong(long I, long J)
{
	long ret;
	ret = (long)(intl_randd()*(double)(J-I+1))+I;
	return ret;
}

//composes map_in_main with map_in_sub, starting the submap where the start index is given
//start index + submap size cannot exceed main map length!
//example: main {0,4,1,2,3}, submap {1,2,0}, startindex 2
//yields: main {0,4,2,3,1}
void mapcompose(std::vector<long > *map_in_main, std::vector<long > *map_in_sub, long indstart)
{
	long I;
	long sz1;
	std::vector<long > sm1;
	sz1 = (long)map_in_sub->size();
	sm1.resize(sz1);

	for(I=0;I<sz1;I++)
	{
		sm1[I] = (*map_in_main)[(*map_in_sub)[I]+indstart];
	}
	for(I=0;I<sz1;I++)
	{
		(*map_in_main)[I+indstart] = sm1[I];
	}

	return;
}

void initialize_map(std::vector<long > *map, unsigned long len)
{
	unsigned long I;
	map->resize(len);
	for(I = 0; I<len; I++)
	{
		(*map)[I] = I;
	}
	return;
}

void concat_map(std::vector<long > *less, long pivot, std::vector<long > *greater, std::vector<long > *submap)
{
	unsigned long I;
	submap->resize(less->size()+greater->size()+1);
	for(I=0;I<less->size();I++)
	{
		(*submap)[I] = (*less)[I];
	}
	(*submap)[less->size()] = pivot;
	for(I=0;I<greater->size();I++)
	{
		(*submap)[I+less->size()+1] = (*greater)[I];
	}

	return;
}

ams_tree1::ams_tree1()
{
	nodes.resize(1);
	first_active = 0;
}

ams_tree1::~ams_tree1()
{
	nodes.resize(0);
	first_active = -1;
}

long ams_tree1::next_active_node()
{
	long I;
	long J = -1;
	bool q = 0;
	for(I=first_active;I<(long)nodes.size()&&q==0;I++)
	{
		if(nodes[I].isactive) {q = 1; J = I;}
	}

	first_active = J;
	return J;
}

long ams_tree1::create_node(long parent)
{
	ams_node1 q;
	long childind;

	q.parent = parent;
	q.isactive = 1;
	nodes.push_back(q);
	childind = nodes.size()-1;
	nodes[parent].children.push_back(childind);

	return childind;
}

ams_node1::ams_node1()
{
	parent = -1;
	children.resize(0);
	pivot_index = 0;
	start_index = 0;
	stop_index = 0;
	isactive = 1;

	return;
}

ams_node1::~ams_node1()
{
	parent = -1;
	children.resize(0);
	pivot_index = 0;
	start_index = 0;
	stop_index = 0;
	isactive = 0;

	return;
}

void invertmap(std::vector<long > *map, std::vector<long > *inv)
{
	vector<long > invmap;
	long I;
	invmap.resize(map->size());
	for(I=0;I<(long)map->size();I++)
	{
		invmap[(*map)[I]]=I;
	}
	inv->resize(invmap.size());
	for(I=0;I<(long)map->size();I++)
	{
		(*inv)[I]=invmap[I];
	}
	return;
}

};
