【问题标题】:Swap method taking an array and two integer indexes of the array as parameters以数组和数组的两个整数索引为参数的交换方法
【发布时间】:2016-04-26 02:29:35
【问题描述】:

以下代码用于快速排序类。在底部,有一个名为 swap 的方法,它应该采用一个数组并交换数组中的两个数字。这在Java中可能吗?换句话说,是否有可能有一个格式为 swap(T[], int, int) 的方法可以在这种情况下工作?我希望我的问题有意义。

public class QuickSort {

public static <T extends Comparable<T>> void sort(T[] table) {
    quickSort(table, 0, table.length - 1);
}

private static <T extends Comparable<T>> void quickSort(T[] table, int first, int last) {
    if (first < last) {
        int pivIndex = partition(table, first, last);
        quickSort(table, first, pivIndex - 1);
        quickSort(table, pivIndex + 1, last);
    }
}

private static <T extends Comparable<T>> int partition(T[] table, int first, int last) {
    T pivot = table[first];
    int up = first;
    int down = last;
    do {
        while ((up < last) && (pivot.compareTo(table[up]) >= 0)) {
            up++;
        }
        while (pivot.compareTo(table[down]) < 0) {
            down--;
        }
        if (up < down) {
            swap(table, up, down);
        } 
    }

    while (up < down);
    swap(table, first, down);
    return down;
}

【问题讨论】:

  • 是的,应该可以正常工作。你试过了吗?
  • 他的缩进很糟糕。这是一个do while 循环。

标签: java arrays sorting quicksort swap


【解决方案1】:

是的,你可以这样做,因为在 Java 中,数组是一个对象,所以当你传递它时,你实际上是在传递它在内存中的地址。然后被调用的函数就可以对其进行操作,而这些变化会在各处反映出来。

您可能在想一些在 C++ 中可以做而在 java 中做不到的事情,那就是swap(int x, int y)。因为 java 中的原始数据值没有地址(无论如何程序员都没有地址),所以无法传递它们的地址,因此它们可以在非本地进行修改。

这有意义吗?

【讨论】:

  • 是的,这是有道理的。那么数组索引的交换方法是否会以与交换原语相同的方式使用临时变量?还是可以直接进行交换?
  • 你想使用一个临时的,并且可能不在同一个数组中(只是交换函数的本地)。或者,您可能会对按位异或运算变得棘手(您可以使用'b = a ^ b; a = a ^ b; b = a ^ b;)。
猜你喜欢
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
相关资源
最近更新 更多