繁体   English   中英

Mergesort互换和比较

[英]Mergesort Swaps and Comparisons

我目前正在一个分析项目中,观察在用Java实现时不同算法的行为。 我从网上获得了一些实现Mergesort算法的代码,现在我需要在10,000个随机生成的整数(1到100,000之间)的数组上运行此代码,并记录进行了多少次交换和比较。

我不确定在代码的哪一点增加计数掉期和比较的变量。 期望值是多少? 由于Mergesort的最佳,最差和平均情况都是nlog(n),这是否意味着我期望交换和比较之和等于10,000 *(10,000的对数基数2)大约= 138,000?

这是代码,我猜想交换仅在原始数组被更改时发生,比较我不太确定:

void MergeSort(int low, int high)
   // a[low : high] is a global array to be sorted.
// Small(P) is true if there is only one element to
// sort. In this case the list is already sorted.
{
   if (low < high) { // If there are more than one element
          // Divide P into subproblems.
          // Find where to split the set.
          int mid = (low + high)/2;
          // Solve the subproblems.
          MergeSort(low, mid);
          MergeSort(mid + 1, high);
          // Combine the solutions.
          Merge(low, mid, high);
   }
}

   void Merge(int low, int mid, int high)
 // a[low:high] is a global array containing two sorted
 // subsets in a[low:mid] and in a[mid+1:high]. The goal
 // is to merge these two sets into a single set residing
 // in a[low:high]. b[] is an auxiliary global array.
 {
     int h = low, i = low, j = mid+1, k;
   while ((h <= mid) && (j <= high)) {
      if (a[h] <= a[j]) { b[i] = a[h]; h++; }
      else { b[i] = a[j]; j++; } i++;
   }
   if (h > mid) for (k=j; k<=high; k++) {
                   b[i] = a[k]; i++;
                }
   else for (k=h; k<=mid; k++) {
           b[i] = a[k]; i++;
        }
   for (k=low; k<=high; k++) a[k] = b[k];

}

我不确定在代码的哪一点增加计数掉期和比较的变量。

我建议您为交换和比较操作创建辅助方法。 这将为您提供增量计数器代码的好位置。

由于Mergesort的最佳,最差和平均情况都是nlog(n),这是否意味着我期望 交换和比较的总和约为 10,000 (对数为2的对数,为10,000)?=

您可以期望的是,比较的数量与n log(n)成正比,其中输入的大小为n

在您的合并功能中,我添加了一个变量计数,该计数将完成总交换次数

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

我实际上是为算法和数据结构中的作业做的。 该线程有点尘土飞扬,但是对于任何可以使用它的人,这就是我得到的:

在您的合并方法中

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

if语句是进行比较的地方,我几乎要说,即使对else语句进行比较,由于if语句失败,也会进行比较。

else语句是开始进行交换的位置,如果在else语句中放置一个计数器,它将计算所有交换。 我通过两次检查数组来确认这一点,一次是在未排序时,另一次是在排序时。 我不是100%对此表示满意,因此我们欢迎您提供任何反馈意见。 在我的作业中比较容易看到,因为我正在对字符串进行排序,这与我的作业中上面发布的Merge函数中的相同行:

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

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

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

mergeSortSwaps和mergeSortComparisons是在构造函数中设置的类变量。 如果我记得该方法,可以将它们重置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM