demo如下:
#include "iostream"
#include <cstring>
int tmp[100];
void mergeSort(int a[], int size) {
if (size <= 1) {
return;
}
int* lp = a;
int lSize = size / 2;
int* rp = a + size / 2;
int rSize = size - lSize;
int* index = tmp;
mergeSort(lp, lSize);
mergeSort(rp, rSize);
for (; lp < a + lSize && rp < a + size; ) {
if (*lp < *rp) {
*index++ = *lp++;
}
else {
*index++ = *rp++;
}
}
if (lp < a + lSize) {
memcpy(index, lp, sizeof(int)*(a + lSize - lp));
}
else if (rp < a + size) {
memcpy(index, rp, sizeof(int)*(a + size - rp));
}
memcpy(a, tmp, sizeof(int)*size);
}
int main() {
int a[] = {13, 54, 2, 4, 1, 88, 42};
mergeSort(a, 7);
for(int i = 0; i < 7; i++) {
std::cout << a[i] << ", ";
}
std::cout << std::endl;
return 0;
}
归并排序最坏的复杂度为O(N * logN);