Merge sort C + + implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.