归并排序

typedef int ElementType;

void Merge_sort(ElementType A[], int N)
{
    ElementType *Item = (ElementType*)malloc(N*sizeof(ElementType));
    
    if(Item)
    {
        Msort(A, Item, 0, N-1);
    }
    else
        Error('空间不足');
} 

void Msort(ElementType A[], ElementType Item[], int L, int R)
{
    if(L < R)
    {
        int center = (L+R)/2;
        Msort(A, Item, L, center);
        Msort(A, Item, center+1, R);
        Merge(A, Item, L, center+1, R); 
    }
}

void Merge(ElementType A[], ElementType Item[], int L, int R, int Rend)
{
    int Lend = R-1;
    int num = Rend-L+1;
    int S = L;
    while(L <= Lend && R <= Rend)
    {
        if(A[L] < A[R])
            Item[S++] = A[L++];
        else
            Item[S++] = A[R++];
    }
    while(L <= Lend)
        Item[S++] = A[L++];
    while(R <= Rend)
        Item[S++] = A[R++];
    
    for(int i = 0; i < num; i++)
        A[Rend-i] = Item[Rend-i];
} 

 

你可能感兴趣的:(归并排序)