Modify the application so that it performs a selection sort or bubble sort. The Clear button's label
Question:
Modify the application so that it performs a "selection sort" or "bubble sort". The Clear button's label should be changed to Toggle Sort and the action performed when it is clicked should be changed to toggle the type of sort performed.
Note: The status label should indicate the number of swaps for either sort. The Sort button's label should change to indicate the current type of sort ("Selection" or "Bubble").
A button's label can be changed with its setLabel method. e.g.
mybutton.setLabel("Wombat");
public class SortPanel extends JPanel implements ActionListener {
private final int pauseInterval = 10; // ms larger number slower animation
private ArrayList original = new ArrayList<>();
private void bubbleSort() {
showStatus("Sorting ...");
boolean swap = true;
int count=0;
int travel=1;
while (swap) {
swap = false;
for (int i = 0; i
if (greaterThan(items[i + 1], items[i])) {
swapItems(items[i], items[i + 1]);
swap = true;
count++;
}
}//for
travel++;
} // while
showStatus("Sort complete, number of swaps = "+count);
} // bubbleSort
/**
* Method that handles the button presses.
*
* @parame The ActionEvent
*/
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "Clear" -> {
for (TextField item : items) {
item.setText("");
}
}
case "Sort" -> {
// original.removeAll(original);
for (TextField item : items) {
original.add(item.getText());
}
bubbleSort();
}
case "Reset" -> {
int i=0;
for (TextField item : items) {
item.setText(original.get(i));
i++;
}
//initItems();
}
default -> showStatus("Unrecognised button: " + e);
}
}
...
public class SortDriver {
public static void main(String[] args) {
JFrame frame = new JFrame("Sorting Algorithms");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 200);
frame.setResizable(false);
SortPanel panel = new SortPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Discrete and Combinatorial Mathematics An Applied Introduction
ISBN: 978-0201726343
5th edition
Authors: Ralph P. Grimaldi