简体   繁体   English

交换方法,以数组和数组的两个整数索引为参数

[英]Swap method taking an array and two integer indexes of the array as parameters

The following code is for a quick sort class. 以下代码用于快速排序类。 Towards the bottom, there is a method called swap which is supposed to take an array and swap two of the numbers in the array. 在底部,有一个称为swap的方法,该方法应该获取一个数组并交换数组中的两个数字。 Is this possible in Java? 这在Java中可行吗? In other words is it possible to have a method in the format of swap(T[], int, int) that will work in this instance? 换句话说,是否有一种格式为swap(T [],int,int)的方法可以在这种情况下使用? I hope my question makes sense. 我希望我的问题有道理。

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

Yes, you can do this, because in Java an Array is an Object, so when you pass it, you're really passing its address in memory. 是的,您可以这样做,因为在Java中,数组是一个对象,所以当您传递它时,实际上就是在内存中传递它的地址。 The called function can then operate on it, and those changes will be reflected everywhere. 然后,被调用的函数可以对其进行操作,并且这些更改将在所有地方反映出来。

You might be thinking of something you can do in C++ that you can't do in java, which is swap(int x, int y) . 您可能正在考虑可以在C ++中完成的某些事情,而在Java中无法做到的,这就是swap(int x, int y) Because primitive data values in java don't have addresses (not ones that are available to the programmer, anyway), there's no way to pass their addresses off so they can be modified non-locally. 因为Java中的原始数据值没有地址(无论如何,程序员都没有可用的地址),所以无法传递其地址,因此可以在非本地修改它们。

Does that make sense? 那有意义吗?

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

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