# Why is this implementation of merge sort not working?

I am missing something embarrassing element in my Merge Sort implementation:

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

int temp;

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 doesn't it work as it should? I checked and checked again but I am not getting a sorted array. What am I missing here?

This is what I get: 1 5 8 7 4 30 -87 100 200 300

You can vote, but I'm very confused myself to ask this here.

+2

source to share

my_merge () concatenates numbers in temp [], but never copies them back to indices []. Copy them back to the correct location and it should work.

+1

source

All Articles