简体   繁体   中英

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. Is this possible in 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? 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. 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) . 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.

Does that make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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