C + + merge sort algorithm Instance _c language

Source: Internet
Author: User

Merge sort

Merging sorting algorithm is a very typical application of partition method. The idea of a merge sort is to divide the numbers in an array into one; for a single number, it is definitely orderly, and then we combine these ordered numbers together to form an orderly sequence. This is the idea of merging sort. Its time complexity is O (N*LOGN).

Code implementation

Copy Code code as follows:

#include <iostream>
using namespace Std;

There will be two ordered series A[first...mid] and A[mid ... Last] Merge.
void Mergearray (int a[], int A, int mid, int last, int temp[])
{
int i = A, J = mid + 1;
int m = Mid, n = last;
int k = 0;

while (I <= m && J <= N)
{
if (A[i] <= a[j])
temp[k++] = a[i++];
Else
temp[k++] = a[j++];
}

while (I <= m)
temp[k++] = a[i++];

while (j <= N)
temp[k++] = a[j++];

for (i = 0; i < K; i++)
A[first + i] = temp[i];
}
void mergesort (int a[], int A, last, int temp[])
{
if (a < last)
{
int mid = (i + last)/2;
MergeSort (A, I, Mid, temp); Left orderly
MergeSort (A, mid + 1, last, temp); Right order
Mergearray (A, I, Mid, last, temp); Then merge the two ordered sequences
}
}

BOOL MergeSort (int a[], int n)
{
int *p = new Int[n];
if (p = = NULL)
return false;
MergeSort (A, 0, n-1, p);
Delete[] p;
return true;
}

int main ()
{
int arr[] = {2, 1, 4};
MergeSort (arr, 3);

for (int i = 0; i < 3; ++i)
{
cout<<arr[i]<< "";
}
cout<<endl;
}

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.