#include <iostream>
#include <string.h>
#include <assert.h>
#include <Windows.h>
using namespace std;
void
MyStrCpy(int* buf, const int* str, int lenth)
{
assert(buf && str && lenth >= 0);
int index = 0;
for (int i = 0; i < lenth; i++) {
*(buf + index++) = str[i];
}
return;
}
void
mergerStr(int* str, int left, int mid, int right, int* tmp)
{
assert(str && tmp);
// 归并排的时候需要一个临时的数组
int i = left; // 记录右边的起始下标
int j = mid; // 记录左边的起始下标
int index = left; // 临时数组的下标
while (i < mid && j <= right) {
if (str[i] < str[j]) {
tmp[index++] = str[i++];
}else {
tmp[index++] = str[j++];
}
}
while (i < mid) {
tmp[index++] = str[i++];
}
while (j <= right) {
tmp[index++] = str[j++];
}
MyStrCpy(str+left, tmp+left, right-left+1);
// memcpy(str + left, tmp + left, right-left+1);
return;
}
void
mergerSort(int* str, int left, int right, int* tmp)
{
assert(str && tmp);
int mid = 0;
if (right > left) {
mid = (left + right) / 2;
mergerSort(str, left, mid, tmp);
mergerSort(str, mid+1, right, tmp);
mergerStr(str, left, mid+1, right, tmp);
}
}
int
main(void)
{
int boy[] = { 9, 6, 1, 48, 13, 25, 21, 17};
// int boy[] = { 9, 6, 15, 48, 13, 25};
// int boy[] = { 3, 9, 11, 14, 9, 19, 21, 23, 29};
int lenB = sizeof(boy) / sizeof(boy[0]);
int* tmp_str = (int*)calloc(lenB, sizeof(int));
mergerSort(boy, 0, lenB-1, tmp_str);
// mergerStr(boy, 0, lenB/2, lenB-1, tmp_str);
// mergerStr_tmp(boy, 0, lenB / 2, lenB);
for (int x : boy) {
cout << x << " ";
}
cout << endl;
free(tmp_str);
system("pause");
return 0;
}