M.H.F
M.H.F

Reputation: 91

Counting the number of comparisons for merge sort

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;
}

Upvotes: 2

Views: 7634

Answers (1)

Aleksandar Makragić
Aleksandar Makragić

Reputation: 1997

Easiest way to accomplish this is to have one global variable count and you increment that variable each time you have comparison in Mergesort code. Either that or using pointers.

In C when you pass argument to function, that argument gets copied so original will remain unchanged. That's the problem with your code.

Please, read more here: Why would I pass function parameters by value in C?

Upvotes: 2

Related Questions