编辑代码

#include <iostream>
#include <math.h>
using namespace std;

bool merge(int array[], size_t arrStart, size_t arrMiddle, size_t arrEnd) {
    int arrLen = arrEnd - arrStart;
    if (arrLen < 2) {
        cout << "Please check your implementation." << endl;
        return false;
    }
    int *temp = new int(arrLen);
    int i = arrStart;
    int j = arrMiddle;
    int tempIndex = 0;
    while (i < arrMiddle && j < arrEnd) {
        if (array[i] > array[j]) {
            temp[tempIndex] = array[j];
            ++j;
        }
        else {
            temp[tempIndex] = array[i];
            ++i;
        }
        ++tempIndex;
    }
    while (i < arrMiddle) {
        temp[tempIndex++] = array[i++];
    }
    while (j < arrEnd) {
        temp[tempIndex++] = array[j++];
    }
    for ((tempIndex = 0, i = arrStart); (tempIndex < arrLen && i < arrEnd); (++tempIndex, ++i)) {
        array[i] = temp[tempIndex];
    }
    delete []temp;
    temp = NULL;
    return true;
}
bool mergeSort(int array[], size_t arrStart, size_t arrEnd) {
    int arrLen = arrEnd - arrStart;
    if (arrLen < 0) {
        cout << "Please check your input." << endl;
        return false;
    }
    if (arrLen == 0 || arrLen == 1) {
        return true;
    } 
    int middle = arrStart + floor(arrLen / 2);
    mergeSort(array, arrStart, middle);
    mergeSort(array, middle, arrEnd);
    return merge(array, arrStart, middle, arrEnd);
}

void printArray(int array[], int arrLen) {
    for (int i = 0; i < arrLen; ++i) {
        cout << array[i] << " ";
    }
    cout << endl;
}
int main() {
    int K[]={11,9,3,20,56,32};
    cout<<"排序前:";
    printArray(K,sizeof(K)/sizeof(int));
    mergeSort(K,0,sizeof(K)/sizeof(int));
    cout<<"排序后:";
    printArray(K,sizeof(K)/sizeof(int));
    return 0;
}