繁体   English   中英

在shell排序中计算比较次数

[英]Counting number of comparisons in shell sort

使用此代码,我必须计算进行元素比较的次数。 话虽如此,我不确定比较是在sort()方法的for循环内还是在less()方法内完成。 非常感谢你的帮助。

    public class Shell {
private static int compares;
// This class should not be instantiated.
private Shell() { }

/**
 * Rearranges the array in ascending order, using the natural order.
 * @param a the array to be sorted
 */
public static void sort(Comparable[] a) {
    int n = a.length;

    // 3x+1 increment sequence:  1, 4, 13, 40, 121, 364, 1093, ... 
    int h = 1;
    while (h < n/3) h = 3*h + 1; 

    while (h >= 1) {
        // h-sort the array
        for (int i = h; i < n; i++) {
            for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) {
                exch(a, j, j-h);
            }
        }
        assert isHsorted(a, h); 
        h /= 3;
    }
    assert isSorted(a);
}

/ ******************* ************************** *帮助程序排序功能。 ************************************************** ******** /

   // is v < w ?
   private static boolean less(Comparable v, Comparable w) {
    return v.compareTo(w) < 0;
   }

// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
    Object swap = a[i];
    a[i] = a[j];
    a[j] = swap;
}

/ ******************* ************************** *检查数组是否已排序-对调试很有用。 ************************************************** ************************ /

    private static boolean isSorted(Comparable[] a) {
      for (int i = 1; i < a.length; i++)
        if (less(a[i], a[i-1])) return false;
      return true;
}

// is the array h-sorted?
private static boolean isHsorted(Comparable[] a, int h) {
    for (int i = h; i < a.length; i++)
        if (less(a[i], a[i-h])){
            return false;
        }
    return true;

}

// print array to standard output
      private static void show(Comparable[] a) {
        for (int i = 0; i < a.length; i++) {
          StdOut.println(a[i]);
    }
}

/**
 * Reads in a sequence of strings from standard input; Shellsorts them; 
 * and prints them to standard output in ascending order. 
 *
 * @param args the command-line arguments
 */
public static void main(String[] args) {
    String[] a = StdIn.readAllStrings();
    Shell.sort(a);
    show(a);
}

}

假设您的代码看起来像经典学生的练习,那么可能会要求您仅对在sort函数内调用的less函数进行的元素比较次数进行计数。 如果我错了,请更新您的问题,并添加对目标的更完整描述。

如您所见,每次调用less函数时都会进行比较。 但是在您的代码段中,甚至less的甚至是比较两个对象的常用方法。 因此,仅当在sort方法中直接调用less函数时,才应计数。 其他情况isSortedisHsorted仅存在于断言中。

为了清楚起见,断言是Java编程语言中的一条语句,它使您能够测试有关程序的假设。

记住,这是您的练习,所以您不应该四处寻找简单的答案,并且我不会编写任何详细的代码解决方案。

但是我可以给您另一个建议,您可以尝试创建一个新方法lessWithCounter ,以less名义被调用到sort方法中。

暂无
暂无

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

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