[英]Why is this merge sort implementation not working?
I am missing something embarrassingly basic here in my Merge Sort implementation: 我在“合并排序”实现中缺少令人尴尬的基本内容:
# 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;
}
Why is not working, as it should? 为什么不正常工作呢? I have checked and re-checked again, but I do not get the sorted array.
我已经检查并再次检查,但是没有得到排序的数组。 What am I missing here?
我在这里想念什么?
This is what I get: 1 5 8 7 4 30 -87 100 200 300 这就是我得到的:1 5 8 7 4 30 -87 100 200 300
You may vote it down, but I am myself very embarassed to ask this here. 您可以投反对票,但是我自己在这里问这个问题很尴尬。
my_merge() merges the numbers into temp[], but never copies them back into indices[]. my_merge()将数字合并到temp []中,但切勿将其复制回index []中。 Copy them back into the correct location and it should work.
将它们复制回正确的位置,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.