我一直在进行合并排序,我已经为它编写了一些代码,但它不能按照给定的算法运行。我完全根据算法做了但似乎有些不对劲。请有人让我知道什么是错的。
#include<stdio.h>
int main(){
int a[] = {5, 3, 2, 4, 9, 1, 11, 6, 10};
mergeSort(a, 0, sizeof(a)/ sizeof(int));
printArray(a);
}
void mergeSort(int a[], int low, int high){
int med;
if(high - low > 1){
med = (high - low) / 2 + low;
mergeSort(a, low, med);
mergeSort(a, med+1, high);
merge(a, low, med, high);
}
}
void printArray(int a[]){
int i;
for(i = 0; i < 9; i++){
printf("%d ", a[i]);
}
printf("\n");
}
void merge(int a[], int low, int med, int high){
int i = 0, j = 0, k = low;
int a1[9];
int a2[9];
for(i = 0; i < med; i++){
a1[i] = a[i];
}
for(i = med; i < high; i++){
a2[i] = a[i];
}
while(i < high - med && j < med - low){
if(a1[i] <= a2[j]){
a[k] = a1[i];
i++;
}else{
a[k] = a2[j];
j++;
}
}
while(i < high - med){
a[k] = a1[i];
i++;
}
while(j < med - low){
a[k] = a2[j];
j++;
}
}
答案 0 :(得分:2)
我不知道你从哪里得到那个算法但是它的结尾(最后2个while循环)是不正确的。你也错误地复制了部分内容。我会遗漏那些没有变化且没必要的东西。
我的所有评论都指出了代码的更改位置。
void mergeSort(int a[], int low, int high){
int med;
if(high - low > 1){
med = (high - low) / 2 + low;
mergeSort(a, low, med);
mergeSort(a, med, high); //you copied this down wrong. med NOT med + 1
merge(a, low, med, high);
}
}
void merge(int a[], int low, int med, int high){
int i = 0;
int j = 0;
int k = low;
int a1[9];
int a2[9];
for(i = 0; i < med; i++){
//algorithm states to copy by doing: a1[0 -> med] = a[low -> med - 1]
//we're copying the subarray 'a' from 'low' to 'med - 1' into
//'a1' from 0 to 'med'
a1[i] = a[i + low];
}
for(i = med; i < high; i++){
//algorithm states to copy by doing: a2[0 -> med] = a[med -> high - 1]
a2[i - med] = a[i];
}
//don't forget to reset i to 0
i = 0;
while(i < med - low && j < high - med){
if(a1[i] <= a2[j]){
a[k] = a1[i];
i++;
}else{
a[k] = a2[j];
j++;
}
k++;
}
while(i < med - low){
a[k] = a1[i];
i++;
k++;
//algorithm didn't have k++ for some reason
}
while(j < high - med){
//note it's a2[j] not a2[i]
//algorithm was wrong here
a[k] = a2[j];
j++;
k++;
//didn't have k++ here either
}
}
最后3个while循环可以通过数组索引中的后增量运算符缩短,因为我们知道我们的意图是在语句完成后递增它们(因此 post -increment)。 / p>
while(i < med - low && j < high - med){
if(a1[i] <= a2[j])
a[k++] = a1[i++];
else
a[k++] = a2[j++];
}
while(i < med - low)
a[k++] = a1[i++];
while(j < high - med)
a[k++] = a2[j++];