java - 在 merge 方法中返回多个变量

标签 java sorting recursion

我编写了一种对值数组进行合并排序的方法。方法工作得很好,但我试图展示已经发生的比较和交流的数量。我的第一个想法是创建静态变量(int 比较、int 交换)并将它们传递到方法中。但是我遇到了从辅助方法返回它们的问题。是否可以在同一个方法中返回一个 int[] 和两个 int ?如果没有,我如何确定已经发生的比较和交换的次数?

这是我的 mergeSort 和合并方法:

    public static int[] mergeSort(int[] A, int comps, int exchs) {
    // Array has only 1 element
    if( A.length <= 1 ) {
        return A;
    }
    int midPoint = A.length / 2;
    // Initialize left and right arrays.
    int[] left = new int[midPoint];
    int[] right = new int[A.length - midPoint];
    System.arraycopy(A, 0, left, 0, midPoint);
    System.arraycopy(A, midPoint, right, 0, A.length - midPoint);
    //recursively sort left and right arrays
    left = mergeSort(left, comps, exchs);
    right = mergeSort(right, comps, exchs);
    System.out.println("Comparisons" + comps);
    System.out.println("Exchanges" + exchs);
    return merge(left, right, comps, exchs);

} 
private static int[] merge(int[] left, int[] right, int comps, int exchs){
    // Initialize the result array.
    int[] res = new int[left.length + right.length];
    // Initialize the array indexes.
    int leftIndex = 0; 
    int rightIndex = 0;
    int resIndex = 0; 
    // compare each element and merge results
    while(leftIndex < left.length && rightIndex < right.length){
        if(left[leftIndex] > right[rightIndex]){
            res[resIndex] = right[rightIndex];
            exchs++;
            rightIndex++;
        } else {
            res[resIndex] = left[leftIndex];
            exchs++;
            leftIndex++; 
        }
        comps++;
        resIndex++;
    }
    comps++;
    // Append remainder of left array into the result array.
    while(leftIndex < left.length){
        res[resIndex] = left[leftIndex];
        exchs++;
        leftIndex++;
        resIndex++;
    }
    comps++;
    // Append whatever is left from the right array into the result array.
    while(rightIndex < right.length) {
        res[resIndex] = right[rightIndex];
        exchs++;
        rightIndex++; 
        resIndex++;
    }
    comps++;
    return res; // want to return comparisons and exchanges to mergeSort method
}

最佳答案

创建一个为您进行排序的对象。然后它可以存储 compsexchs 并且您可以使用 getter 方法访问它们...

public class MergeSorter {
  private int comps = 0;
  private int exchs = 0;

  public int[] mergeSort(int[] A) {
    comps = 0;
    exchs = 0;
    // your code
  }
  private int[] merge(int[] left, int[] right) {
    // your code
  }

  public int getLastComps() { return comps; }
  public int getLastExchs() { return exchs; }
}

关于java - 在 merge 方法中返回多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13728823/

相关文章:

python - 带有递归调用的 return 语句如何在 Python 中保存中间值?

java - 设置hibernate时未找到sessionImplementor类

c - 如何快速排序用户输入

C:如何按最小数字对文件进行排序(使用结构)?

recursion - Prolog::f(x) 递归

c - 不完整的 C 递归函数。我不知道如何正确实现

java - 命令设计模式

java - java 的 make 文件有问题

java - java中的原始类对象

java - 二维数组多次移动选择排序