/*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.

	Dependencies:
		stl vector

*/

/*
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.
*/

#ifndef AMS_QSORT_HPP_
#define AMS_QSORT_HPP_

//an implementation of quicksort for sorting lists and lists of lists by an index list


//Takes a vector of some variable, and a pointer to a vector of indices.
//Takes a comparator function pointer comparator(A,B) which returns true if A > B
//Returns an index map which, when applied to the vector V, will sort V ascending according to the comparator
//template<typename T> bool quicksort_1(std::vector<T> *V, std::vector<long> *map, bool (*comparator)(T, T));

//apparently I have to haul all my definitions into the header file, because C++ doesn't allow definitions of function templates
//outside of the header file. What a pain!

namespace ams_qsort
{

double intl_randd();
long intl_randlong(long I, long J);
void mapcompose(std::vector<long > *map_in_main, std::vector<long > *map_in_sub, long indstart);
void initialize_map(std::vector<long > *map, unsigned long len);
void concat_map(std::vector<long > *less, long pivot, std::vector<long > *greater, std::vector<long > *submap);
void invertmap(std::vector<long > *map, std::vector<long > *inv);

class ams_node1
{
public:
	long parent;
	std::vector<long > children;
	long pivot_index;
	long start_index;
	long stop_index;
	bool isactive;

	ams_node1();
	~ams_node1();
};

class ams_tree1
{
public:
	std::vector<ams_node1 > nodes;
	long first_active; //index of first active node

	long create_node(long parent); //returns pointer to new node

	long next_active_node();
	ams_tree1();
	~ams_tree1();
};

//comparator(A,B)
//comparator returns true if A greater than B
template<typename T> void sort_node(std::vector<T> *V, std::vector<long > *map, bool (*comparator)(T , T), ams_tree1 *tree, long nodeindex)
{
	long start = tree->nodes[nodeindex].start_index;
	long stop = tree->nodes[nodeindex].stop_index;
	long pivot = tree->nodes[nodeindex].pivot_index;
	long I;

	std::vector<long > submap;
	std::vector<long > less;
	std::vector<long > greater;

	//if list is size 1, do nothing, else
	if(stop-start>0)
	{
		less.resize(0);
		greater.resize(0);
		for(I=start;I<=stop;I++)
		{
			if(I!=pivot) //for all indices except the pivot index
			{
				if(comparator((*V)[(*map)[I]],(*V)[(*map)[pivot]]))
				{
					greater.push_back(I-start); //if I > pivot, sort into greater list
				}
				else
				{
					less.push_back(I-start); //else sort into less list
				}
			}
		}
		//concatonate the maps
		concat_map(&less,pivot-start,&greater,&submap);
		//compose submap with main map
		mapcompose(map,&submap,start);
		//spawn new nodes
		//node for less than pivot
		if(less.size()>0)
		{
			I = tree->create_node(nodeindex);
			tree->nodes[I].start_index = start;
			tree->nodes[I].stop_index = start+less.size()-1;
			tree->nodes[I].pivot_index = intl_randlong(start,start+less.size()-1);
			tree->nodes[I].isactive = 1;
		}
		//node for greater than pivot
		if(greater.size()>0)
		{
			I = tree->create_node(nodeindex);
			tree->nodes[I].start_index = start+less.size()+1;
			tree->nodes[I].stop_index = start+less.size()+1+greater.size()-1;
			tree->nodes[I].pivot_index = intl_randlong(start+less.size()+1,start+less.size()+1+greater.size()-1);
			tree->nodes[I].isactive = 1;
		}
	}
	tree->nodes[nodeindex].isactive = 0;

	return;
}

//Takes a vector of some variable, and a pointer to a vector of indices.
//Takes a comparator function pointer comparator(A,B) which returns true if A > B
//Returns an index map which, when applied to the vector V, will sort V ascending according to the comparator
template<typename T> bool quicksort(std::vector<T> *V, std::vector<long> *map, bool (*comparator)(T, T))
{
	bool ret = 0;
	long J;
	initialize_map(map,V->size());
	ams_tree1 *tree = new ams_tree1();
	tree->nodes[0].isactive = 1;
	tree->nodes[0].start_index = 0;
	tree->nodes[0].stop_index = V->size()-1;
	tree->nodes[0].pivot_index = intl_randlong(0,V->size()-1);

	J = 0;
	while(J!=-1)
	{
		sort_node(V,map,comparator,tree,J);
		J = tree->next_active_node();
	}



	delete tree;
	return ret;
}

//applies an index map to the vector V and rearranges it accordingly.
template<typename T> bool rearrange(std::vector<T> *V, std::vector<long> *map)
{
	bool ret = 1;
	std::vector<T> V2;
	long I;

	if(V->size()==map->size())
	{
		V2.resize(V->size());
		for(I=0;I<(long)V->size();I++)
		{
			V2[I] = (*V)[(*map)[I]];
		}
		for(I=0;I<(long)V->size();I++)
		{
			(*V)[I]=V2[I];
		}
	}
	else
	{
		ret = 0;
	}

	return ret;
}

};

#endif /* AMS_QSORT_HPP_ */
