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;
}