I'm trying to implement the merge sort in c, but I have a segmentation fault 11, and I don't get why.
void trieFusion(int *t, int d, int f){
if (f==d)
return;
int m=(f-d)/2+d;
trieFusion(t, d, m);
trieFusion(t, m+1, f);
int tmp[(f-d+1)];
int pg = d;
int pd = m + 1;
for(int i = d; i <= f; i++) {
if(pg == m + 1) {
tmp[i] = t[pd];
pd++;
}
else if (pd == f + 1) {
tmp[i] = t[pg];
pg++;
}
else if (t[pg] < t[pd]) {
tmp[i] = t[pg];
pg++;
}
else{
tmp[i] = t[pd];
pd++;
}
}
for(int i = d; i <= f; i++) {
t[i] = tmp[i];
}
}
The main
int main(){
int t[] = {2,4,2,4,6,7,2,3,5,4};
int n=10;
afficheTableau(t, n);
majoritaireNLogN(t, n);
afficheTableau(t,n);
return EXIT_SUCCESS;
}
The function that calls my merge sort
int majoritaireNLogN(int* t, int n){
n--;
trieFusion(t, 0, n);
return t[0];
}
If I run my code, I can sort the first half of a table without a problem, but the segmentation fault is coming from the second half of a table.
I don't find where this problem is coming from.