#include "ProlificScheduler.hpp"
#include <sys/wait.h>

ProlificScheduler::ProlificScheduler() { }
ProlificScheduler::~ProlificScheduler() { }

int ProlificScheduler::partition(double* s, int low, int high) {
	double pivot = s[high];
        int i = low - 1;
        for (int j = low; j < high; ++j) {
        	if (s[j] < pivot) {
                	++i;
                        double temp = s[i];
                        s[i] = s[j];
                        s[j] = temp;
                        }
                   }
                  double temp = s[i + 1];
                  s[i + 1] = s[high];
                  s[high] = temp;
return i + 1;
}

void ProlificScheduler::quick_sort_recursive(double* s, int low, int high) {
    if (low < high) {
            int pi = partition(s, low, high);
            quick_sort_recursive(s, low, pi - 1);
            quick_sort_recursive(s, pi + 1, high);
              }


    }


void ProlificScheduler::execute(int k, int rows, double* data, int n) {
    for (int i = 0; i < k; ++i) {
            if (fork() == 0) {
                        for (int r = i; r < rows; r += k) {
                        quick_sort_recursive(data + (r * n), 0, n - 1);
                         }
                        _exit(0);
                      }
               }
      while (wait(NULL) > 0);
 }
