【问题标题】:Merge Sort Comparison Counter合并排序比较计数器
【发布时间】:2013-05-07 00:01:25
【问题描述】:

我似乎不知道在 Merge 类中将比较计数器放在哪里。尽管它对数组进行了完美的排序,但它不会计算它进行的交换(或比较)的次数。请帮助这是我最终项目的一部分

      public static int mergeSort(int[] intArray, int first, int last) {
        if(first < last) {
          int mid = (first + last) / 2;
          mergeSort(intArray, first, mid);
          mergeSort(intArray, mid + 1, last);
          Merge(intArray, first, mid, last);

     }

     return comparisons;

  }

  public static int Merge(int[] intArray, int first, int mid, int last) {

     //int count = 0;
     comparisons = 0;
     int first1 = first, last1 = mid;
     int first2 = mid + 1, last2 = last;
     int temp[] = new int[intArray.length];
     int index = first1;

     while(first1 <= last1 && first2 <= last2) {
        if(intArray[first1] < intArray[first2]) {
           temp[index] = intArray[first1++];
           comparisons++;
        }
        else
            temp[index] = intArray[first2++];
            index++;
            comparisons++;
     }

     while(first1 <= last1)
        temp[index++] = intArray[first1++];

     while(first2 <= last2)
        temp[index++] = intArray[first2++];

     for(index = first; index <= last; index++)
        intArray[index] = temp[index];


     return comparisons;
  }

【问题讨论】:

  • 您是否从其他人那里复制了此代码?与编写mergeSort 的任务相比,放置comparisons 的位置是微不足道的
  • 还请记住,仅仅因为您缩进了,并不意味着代码会在没有正确括号的情况下执行。你的 else 缺少括号。

标签: java sorting comparison mergesort


【解决方案1】:

在您在这里包含的代码中,您没有显示变量comparisons 的定义,但是由于您使用它而不定义它,我假设它是您类中的一个字段。如果是这样的话,我认为问题在于Merge 中的这一行:

comparisons = 0;

由于您有一个比较次数的全局计数器,因此该行的存在意味着无论何时您调用Merge,您都会将比较总数重置为零,即使在执行过程中也是如此合并排序你已经做了一堆比较。

作为快速修复,只需删除此行。但是,我认为您最好通过根本不将其作为字段并使用返回值来传达所进行的比较次数来解决此问题。这是执行此操作的一种方法:

  public static int mergeSort(int[] intArray, int first, int last) {
    int compares = 0;
    if(first < last) {
      int mid = (first + last) / 2;
      compares += mergeSort(intArray, first, mid);
      compares += mergeSort(intArray, mid + 1, last);
      compares += Merge(intArray, first, mid, last);

 }

 return compares;

}

public static int Merge(int[] intArray, int first, int mid, int last) { 整数比较 = 0; int first1 = first, last1 = mid; int first2 = mid + 1, last2 = 最后一个; int temp[] = new int[intArray.length]; int index = first1;

 while(first1 <= last1 && first2 <= last2) {
    if(intArray[first1] < intArray[first2]) {
       temp[index] = intArray[first1++];
       comparisons++;
    }
    else
        temp[index] = intArray[first2++];
        index++;
        comparisons++;
 }

 while(first1 <= last1)
    temp[index++] = intArray[first1++];

 while(first2 <= last2)
    temp[index++] = intArray[first2++];

 for(index = first; index <= last; index++)
    intArray[index] = temp[index];


 return comparisons;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-19
    • 2013-04-30
    • 1970-01-01
    • 2015-07-09
    • 2017-07-25
    • 2018-05-30
    • 2015-06-30
    • 1970-01-01
    相关资源
    最近更新 更多