Senior sort of - sort merge

Merge sort: thinking in a nutshell is the use of recursive divide and conquer. The number of columns in a disorderly, use half is divided into two columns, and so until the number of elements in each recursive decimal column is to 1, and then let the father of two is a number of columns, sort, just the beginning of each each large numbers listed as number 1, a direct comparison of the size of the sort, and then return later to form the columns are ordered, so let them compare the beginning of sort.

Complexity of O (nlogn), for analysis of n elements is divided into a tree structure, a large number of appointments is a bottom n is 2, then compare each layer is O (n).

Merge sort template code:

#include <the iostream>
#include <cstdio>
the using namespace STD;
const int + MAXN 5E5 = 10; // may be the maximum number of elements in the sorting sequence
int s [maxn / 2 + 2 ], c [maxn / 2 + 2 ]; // extra memory space for storing each time two numbers ordered comparison sorted column
void mergesort (int a [], int left, int right); // the large numbers into decimal columns columns (recursive ) [left, right) habit, left and right open and closed
void merge (int a [], int left, int mid, int right); // the decimal columns were combined to be larger than the number of columns (regression)
int main ()
{
int a [maxn], n; // n number of elements each sort, int type sorting element
CIN n->>;
for (int I = 0; I <n-; I ++)
Scanf ( "% D", a & [ I]);
mergesort (A, 0, n-);
for (int I = 0; I <n--. 1; I ++)
the printf ( "% D", A [I]);
the printf ( "% D \ n-", A [n--. 1]);
return 0;
}
void mergesort (A int [], int left,int right)
{
if(left+1>=right) return ;
MID = int (left + right) / 2;
mergesort (A, left, MID);
mergesort (A, MID, right);
the Merge (A, left, MID, right); // note the location of this call
}
void the Merge (int a [], int left, int MID, int right)
{
for (int I = 0; I <MID-left; I ++) two series of elements // will sort stored in the array s and c,
s [I] = A [left + I];
for (int I = 0; I <right-MID; I ++)
C [I] = A [MID + I];
for (int I = left, J = 0, K = 0; i <right; i ++) // [left, right) is that the two series of elements originally in a position in the array, should remain unchanged after sorting position
{
IF (S [J] <= C [K] ) a [i] = s [ j], j ++; // make less number belongs stable sort merge sort, if the number was less than unstable sort
the else A [I] = C [K], K ++;
IF (J = = MID-left)
{
for (I ++; I <right; I ++)
A [I] = C [K], K ++;
BREAK;
}
IF (K == right-MID)
{
for (I ++; I <right; I ++ )
a[i]=s[j],j++;
break;
}
}
}

Guess you like

Origin www.cnblogs.com/sunjianzhao/p/11356603.html