// parallel sort.cpp : definisce il punto di ingresso dell'applicazione console.
//

#include "stdafx.h"
#include <list>
template <class B,class T >
B  Add(T a, T b) //C++ function template sample
{
	
	return  a+b ;
}
template <class T>
void stampa (T i) {
  cout << " " << i;
}

void aspetta(){	char cc;
cout << endl << " inserisci un carattere per proseguire " << endl;
	cin >> cc;}

int _tmain(int argc, _TCHAR* argv[])
{
	
	
	list<int> a,b,c;
	double t_start,t_end;
#define PROB_SIZE 12000000
	for(unsigned int i=0;i<PROB_SIZE;i++) b.push_back(rand() % 100 + 1);
	t_start=omp_get_wtime();
	b.sort();
	t_end=omp_get_wtime();
	cout << " Tempo Scalare : " << t_end-t_start << endl;
	b.clear();
	for(unsigned int i=0;i<PROB_SIZE;i++) b.push_back(rand() % 100 + 1);
	t_start=omp_get_wtime();
	int NPROCS=omp_get_num_procs();
	omp_set_num_threads(NPROCS);
	vector<list<int>::iterator> itstart(NPROCS),itend(NPROCS);
	vector<list<int>> localist(NPROCS);
	int chunksize=b.size()/NPROCS;
	
#pragma omp parallel 
	{
		int TID=omp_get_thread_num();
		itstart[TID]=itend[TID]=b.begin(); 
		for (int i=0; i<chunksize*TID; i++) itstart[TID]++; // Ma ti pare che devo fare un ciclo per calcolare un puntatore ?!
		for (int i=0; i<chunksize*(TID+1); i++) itend[TID]++; // E' una lista quindi si fa cosė.....
		localist[TID].assign(itstart[TID],itend[TID]);
		localist[TID].sort();// Ciascuno riordina il suo pezzo.
#pragma omp barrier // Quando tutti sono pronti
	int i=2;
		while (i<=NPROCS) 
		{
		if (TID%i==0) localist[TID].merge(localist[TID+(i/2)]);
		i+=i;		
#pragma omp barrier
		}
	}
	t_end=omp_get_wtime();
	cout << "Tempo parallelo"<< t_end-t_start<< endl;
	//localist[0].merge(localist[2]);
	/*for(int i=0;i<NPROCS;i++) 
	{
		for_each(localist[i].begin(),localist[i].end(),stampa<int>);
		
	}*/
	aspetta();
	return 0;

}

