1

Can someone, please, tell me, how to rewrite this quicksort into descending quicksort? Don't mind the Swing part. .........

    public synchronized void quickSort(ArrayList<JButton> randombuttons, int lb, int rb, JPanel random, GridLayout gl, Font font) {
    int lm = lb;
    int rm = rb;
    int pivot = Integer.parseInt(randombuttons.get((lm + rm) / 2).getText());
    do {
        while (Integer.parseInt(randombuttons.get(lm).getText()) < pivot) {
            lm++;
        }
        while (Integer.parseInt(randombuttons.get(rm).getText()) > pivot) {
            rm--;
        }
        if (lm <= rm) {
            if (lm < rm) {
                String tmp2 = randombuttons.get(lm).getText();
                randombuttons.get(lm).setText(randombuttons.get(rm).getText());
                randombuttons.get(rm).setText(tmp2);
                randomplacer(randombuttons, random, gl, font);
            }
            lm++;
            rm--;
        }
    } while (lm <= rm);
    if (lm < rb) {
        quickSort(randombuttons, lm, rb, random, gl,font);
    }
    if (lb < rm) {
        quickSort(randombuttons, lb, rm, random, gl, font);
    }
}
Alex Shkom
  • 11
  • 1
  • Think about how general sorting works: it determines which elements come first when iterating an array or list front to back. It does so by comparing the elements and generic implementations use a `Comparator` for this. To revert the order you don't change the algorithm but how elements are compared: if you want to sort strings in descending order, change the comparison so that "b" < "a" and you'de done (in your case the comparison would be those `Integer.parseInt(...) < pivot` and `Integer.parseInt(...) > pivot` portions). – Thomas Jul 28 '21 at 13:48
  • See: https://stackoverflow.com/questions/7414299/sorting-int-array-in-descending-order/7414379 – TedEd Aug 10 '21 at 14:51

1 Answers1

0

You should just flip the comparison operator where it is used to compare values (as opposed to indices). In this Quick Sort implementation, a value comparison always involves the pivot value.

There are two places where you have such a value comparison (using < and >):

while (Integer.parseInt(randombuttons.get(lm).getText()) < pivot) {
    lm++;
}
while (Integer.parseInt(randombuttons.get(rm).getText()) > pivot) {
    rm--;
}

Just inverted them (< to > and vice versa).

trincot
  • 317,000
  • 35
  • 244
  • 286