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[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;
                y = (x+z)/2;

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++];
                        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; 

                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.


source to share

1 answer

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



All Articles