我正在尝试实现合并排序,但我无法让它工作。如果有人能找到并指出我的想法(和代码)中的错误,我将不胜感激。
没有不必要代码的主要功能:
int main(int argc, char *argv[]) {
int n = 0;
std::cin >> n;
int num[n];
for(int i = 0; i < n; i++) {
std::cin >> num[i];
}
sort(num, &num[n - 1], n);
return(0);
}
合并排序功能:
int *sort(int *s, int *e, int size) {
if(s == e) {
return(s);
}
int mid = (size + 1) / 2;
//split array recursively to 1-element arrays
int *left = sort(s, (s + mid - 1), mid);
int *right = sort(s + mid, e, size - mid);
int *counter = s;
//merge arrays back together
while(left < (s + mid - 1) && right <= e) {
//std::cout << *left << " " << *right << std::endl;
for(; left < (s + mid - 1) && *left <= *right; left++, counter++) {
*counter = *left;
}
for(; right <= e && *right <= *left; right++, counter++) {
*counter = *right;
}
}
for(; left < (s + mid - 1); left++, counter++) {
*counter = *left;
}
for(; right <= e; right++, counter++) {
*counter = *right;
}
return(s);
}
输入0 :
5
4 3 2 1 0输出0
:
0 0 0 0 0输入1:
5
0 1 2 3 4
输出1:
1 2 4 4 4输入 2:
2
0 1
输出 2:
1 1