Merge sort
#include <iostream>
#include <functional>
#include <memory>
#include <array>
using namespace Std;
void Merge_sort (array<int,5>&, int);
int main ()
{
Array<int, 5> arr = {1, 5, 2, 4, 3};
Merge_sort (arr, 5);
for (auto I:arr)
cout << i << Endl;
Cin.get ();
return 0;
}
void Merge_sort (array<int,5>& arr, int cont)
{
Function<void (array<int,5>&, int, int, int) > Merge = [&] (array<int,5>& arr_, int first, int mid, int last)
{
if (first >= last)//is stopped only if it is coincident with the final one, because only two of them need to be sorted
{
Return
}
Merge (Arr_, First, MID/2, mid); Recursion makes the left part orderly
Merge (Arr_, Mid + 1, (Mid + 1 + last)/2, last); Recursion makes the right half of the part orderly
The following code must be placed below, in order to enable the final processing of the original integer group
Unique_ptr<int[]> temp (new int[last+1]); The last one here is the actual subscript, so add 1.
int f = First; To save first and finally merge into the original array, use the
int t = mid + 1;
int k = 0;
Until a part of it is done. Note: to include the last element
while (first <= mid && T <= last)
{
if (Arr[first] < arr[t])
{
temp[k++] = arr[first++];
}
Else
{
temp[k++] = arr[t++];
}
}
To finish the rest of the work.
if (First > mid)//This can actually omit the if statement, directly written in two while, but for the readability of the code, we add the IF statement
{
while (T <= last)
{
temp[k++] = arr[t++];
}
}
Else
{
while (first <= mid)
{
temp[k++] = arr[first++];
}
}
Combine the two parts of the comparison to put them in the original array
for (int i = 0; i < K; i++)
{
Arr[f + i] = temp[i];
}
};
Merge (arr, 0, (cont-1)/2, cont-1);
}
Merge sort C + + implementation