Mergesort Swaps and Comparisons

若如初见. 提交于 2019-12-06 09:02:30

I'm not exactly sure at which point in the code to increment the variables that count Swaps and Comparisons.

I suggest you create helper methods for the swap and the compare operation. That would give you good places for the increment-counter code.

Since best, worst, and average case for Mergesort are all nlog(n) does this mean I should expect 10,000(log base 2 of 10,000) approx = 138,000 for the sum of swaps and comparisons?*

What you can expect is that the number of comparisons is proportional to n log(n) where the size of the input is n.

In Your Merge Function i added a variable count which will have the number of total swaps done

  while ((h <= mid) && (j <= high)) {
      if (a[h] <= a[j]) { b[i] = a[h]; h++; }
      else { b[i] = a[j]; j++; count+=mid-h+1; } i++;
  }

I'm actually doing this for Homework in Algorithms and Data Structures. The thread is a bit dusty but for anyone who could use it this is what I got:

In your Merge method

while ((h <= mid) && (j <= high)) {
  if (a[h] <= a[j]) { b[i] = a[h]; h++; }
  else { b[i] = a[j]; j++; } i++;
}

the if statement is where the comparison is being made, I almost want to say that even if you make it to the else statement a comparison is made as well due to the if statement failing.

The else statement is where the swap starts to be made, if you put a counter in the else statement it will count up all the swaps. I confirmed this by checking the array twice, once when unsorted and again when sorted. I'm not 100% on this so any feedback is appreciated. It's a little easier to see in my assignment because I'm sorting strings, these are the same lines in your Merge function posted above, from my assignment:

while(leftPos<=leftEnd && rightPos<=rightEnd)
{
    mergeSortComparisons++;

    if (a[leftPos].compareTo(a[rightPos]) <= 0)     
        tmpArray[tmpPos++]=a[leftPos++];

    else 
    {
        tmpArray[tmpPos++]=a[rightPos++];
        mergeSortSwaps++;
    }
}

mergeSortSwaps and mergeSortComparisons are class variables that are set in the constructor. I can reset them if I recall the method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!