归并排序

代码

#include<iostream>
#define N 8
#define ElemType int
ElemType *B = (ElemType *)malloc((N + 1) * sizeof(ElemType));
/*输出数组*/
void OutPrint(ElemType A[]) {
    int i;
    for (i = 0; i <N; i++)
    {
        printf("%d  ", A[i]);
    }
}
/*归并排序*/
void Merge(ElemType A[], int low, int mid, int high) {
    int i,j,k;
    for (int k = low; k <= high;k++)
        B[k] = A[k];
    for (i = low, j = mid + 1, k = i; i <= mid && j <= high; k++) {
        if (B[i] <= B[j])
            A[k] = B[i++];
        else
            A[k] = B[j++];
    }
    while (i <= mid) A[k++] = B[i++];
    while (j <= high)  A[k++] = B[j++]; 
}   
void MergeSort(ElemType A[], int low,int high) {
    if (low<high) {
        int mid = (low + high) / 2;
        MergeSort(A, low, mid);
        MergeSort(A, mid + 1, high);
        Merge(A, low, mid, high);
    }
}
int main() {
    ElemType A[N] = { 48, 62, 35, 77, 55,14,35,98 };
    printf("排序前数组\n");
    OutPrint(A);
    MergeSort(A, 0, N - 1);
    printf("\n排序后数组\n");
    OutPrint(A);
    system("pause");
    return 0;
}

结果如图:
归并排序

上一篇:线性表


下一篇:顺序表一些基本操作