en C++, mais vous pouvez simplement utiliser des tableaux au lieu de vecteurs pour C
#include <iostream>
#include <vector>
// merge 2 arrays using a temp array
void merge (std::vector<int>& v, std::vector<int>& tmpArray, int left, int center, int right)
{
int leftPos = left;
int leftEnd = center;
int tmpPos = leftPos;
int rightEnd = right;
int rightPos = center + 1;
// finger matching algo left and right
while (leftPos <= leftEnd && rightPos <= rightEnd)
{
// this first if block here for equals is what does your duplicate removal magic
if (v[leftPos] == v[rightPos])
{
tmpArray[tmpPos++] = std::move(v[leftPos++]);
++rightPos;
}
else if (v[leftPos] < v[rightPos])
tmpArray[tmpPos++] = std::move(v[leftPos++]);
else
tmpArray[tmpPos++] = std::move(v[rightPos++]);
}
// copy rest of left
while (leftPos <= leftEnd)
tmpArray[tmpPos++] = std::move(v[leftPos++]);
// copy rest of right
while (rightPos <= rightEnd)
tmpArray[tmpPos++] = std::move(v[rightPos++]);
// copy tmp array back to array
int numElements = right - left + 1;
for (int i = 0; i < numElements; ++i, --rightEnd)
v[rightEnd]=std::move(tmpArray[rightEnd]);
}
void mergeSort (std::vector<int>& v, std::vector<int>& tmpArray, int left, int right)
{
if (left < right)
{
auto center = left + (right - left)/2;
mergeSort(v, tmpArray, left, center);
mergeSort(v, tmpArray, center+1, right);
merge (v, tmpArray, left, center, right);
}
}
void mergeSort (std::vector<int>& v)
{
int sz = v.size();
std::vector<int> tmpArray (sz, 0);
mergeSort (v, tmpArray, 0, sz-1);
}
int main()
{
std::vector<int> v { 7,8,6,5,4,3,9,12,14,17,21,1,-2,-3,-3,-3,-9,10,11 };
mergeSort (v);
for (auto&i : v)
std::cout << i << " " ;
std::cout << std::endl;
}
Cette réponse a répondu à la question recusively. – pierrotlefou
jetez un oeil aux instructions pour Mergesort. – monksy