繁体   English   中英

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

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

以下代码用于快速排序类。 在底部,有一个称为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;
}

是的,您可以这样做,因为在Java中,数组是一个对象,所以当您传递它时,实际上就是在内存中传递它的地址。 然后,被调用的函数可以对其进行操作,并且这些更改将在所有地方反映出来。

您可能正在考虑可以在C ++中完成的某些事情,而在Java中无法做到的,这就是swap(int x, int y) 因为Java中的原始数据值没有地址(无论如何,程序员都没有可用的地址),所以无法传递其地址,因此可以在非本地修改它们。

那有意义吗?

暂无
暂无

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

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