So this is my code for a merge sort. But I need to find out how many times the comparisons were made during the merge function. For my code, the count output would be 0. How should I change the code to make the counter working?
#include<stdio.h>
#include<stdlib.h>
void merge(int *array,int low, int mid, int high,int count)
{
int i=low, j=mid+1, n=low, f[high+1];
while((i<=mid)&&(j<=high)) {
if(array[i]>array[j]){
f[n]=array[j];
j++;
}else{
f[n]=array[i];
i++;
}
n++;
count++;
}
if(i>mid)
while(n<=high) {
f[n]=array[j];
n++;
j++;
}
if(j>mid)
while(n<=high) {
f[n]=array[i];
n++;
i++;
}
for(n=low;n<=high;n++)
array[n]=f[n];
}
void mergesort(int *array, int low, int high,int count)
{
int mid;
if(low<high){
mid=(high+low)/2;
mergesort(array,low,mid,count);
mergesort(array,mid+1,high,count);
merge(array, low, mid, high,count);
}
}
int main()
{
int size,i, count=0, *f;
scanf("%d", &size);
f=(int *)malloc(sizeof(int)*size);
for(i=0;i<size;i++)
scanf("%d", &f[i]);
mergesort(f, 0, size-1,count);
for(i=0;i<size;i++) {
printf("%d",f[i]);
if(i==size-1)
printf("\n");
else
printf(" ");
}
printf("%d\n", count);
return 0;
}