ghost-in-the-shell

The swap method takes an array and two integer array indices as arguments

The code below is for a rapid sort class. There is a function named swap near the bottom that is intended to accept an array and swap two of the integers in the array. Is this something that Java can do? Is it feasible to have a method in the format swap(T, int, int) that will function? I think my question is clear.
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;
}
Share on Facebook
Share on X (Twitter)
Share on Reddit
Share on Linkedin
Share on Hacker News

Content-ID: 4720234988

Url: https://rootdb.com/forum/the-swap-method-takes-an-array-and-two-integer-array-indices-as-arguments-4720234988.html

Printed on: May 19, 2025 at 23:05 o'clock

ghost-in-the-shell
Solution ghost-in-the-shell Nov 22, 2022 at 14:03:45 (UTC)
Goto Top
ghost-in-the-shell
ghost-in-the-shell Nov 30, 2022 at 13:32:14 (UTC)
Goto Top

Thanks for the help! It really help.