Você está na página 1de 2

#include "MergeSort.

h"
#include <iostream>
using namespace std;
double* MergeSort::sort(double* v, int sizeV)
{
if(sizeV == 2){
if(v[1] < v[0])
{
//switch
double temp = v[0];
v[0] = v[1];
v[1] = temp;
}
return v;
}
if(sizeV == 1){
return v;
}
int half = sizeV/2;
if(sizeV % 2 == 0)
{
half--;
}
double* leftV = sort(subArray(v, 0, half), half+1);
double * rightV = sort(subArray(v,half+1,sizeV-1), sizeV - half - 1);
return orderSubArrays(leftV, rightV, half+1, sizeV - half - 1);
}
double* MergeSort::subArray(double* v, int begginV, int endV)
{
int subVSize = (endV - begginV)+1;
int counter = 0;
double* subV = new double[subVSize];
for(int i = begginV; i < endV + 1; i++)
{
subV[counter++] = v[i];
}
return subV;
}
double* MergeSort::orderSubArrays(double* leftV, double* rightV, int sizeLeftV,
int sizeRightV)
{
int countLeft = 0;
int countRight = 0;
int countOrdered = 0;
double* orderedV = new double[sizeLeftV+sizeRightV];
while(countLeft < sizeLeftV || countRight < sizeRightV)
{
if(countLeft == sizeLeftV)
{
orderedV[countOrdered++] = rightV[countRight++];
}
else if(countRight == sizeRightV)

{
orderedV[countOrdered++] = leftV[countLeft++];
}
else if(rightV[countRight] <= leftV[countLeft])
{
orderedV[countOrdered++] = rightV[countRight++];
}
else if(leftV[countLeft] < rightV[countRight])
{
orderedV[countOrdered++] = leftV[countLeft++];
}
}
return orderedV;
}

Você também pode gostar