为什么这种合并排序实现不起作用?

时间:2009-09-03 14:39:42

标签: algorithm sorting

我在Merge Sort实现中遗漏了一些令人尴尬的基本内容:

# include <math.h>
# include <stdio.h>

int temp[10];

void merge_sort(int *indices, int x, int z);
void m_merge(int *indices, int x, int y, int z);


void merge_sort(int *indices, int x, int z )
{
        int y;
        if(x<z){
                y = (x+z)/2;
                merge_sort(indices,x,y);
                merge_sort(indices,y+1,z);
                my_merge(indices,x,y,z);
        }
}

void my_merge(int *indices, int x, int y, int z)
{
        int mark1=x, mark2=y+1;
        int cnt=0;

        while(mark1 <= y && mark2 <= z){
                if (indices[mark1] < indices[mark2])
                        temp[cnt++] = indices[mark1++];
                else
                        temp[cnt++] = indices[mark2++];
        }
        while(mark1 <= y)
                temp[cnt++] = indices[mark1++];

        while(mark2 <= z)
                temp[cnt++] = indices[mark2++];

}

int main(int argc, char **argv)
{
        int arr[] = {1,5,8,7,4,30,-87,100,200,300};
        int i; 
        merge_sort(arr,0,9);

        for(i=0;i<=9;i++)
                printf(" %d \n  ",temp[i]);

        return 0;
}

为什么不能正常工作?我已经检查并重新检查,但我没有得到排序的数组。我在这里错过了什么?

这是我得到的:1 5 8 7 4 30 -87 100 200 300

你可以投票,但我自己很尴尬在这里问这个。

1 个答案:

答案 0 :(得分:1)

my_merge()将数字合并到temp []中,但从不将它们复制回indices []。将它们复制回正确的位置,它应该可以工作。

相关问题