I need help on using bubble sort and sorting it whether ascending or descending :(
int[] number = {12, 5, 6, 14, 18};
int[] number = new int[5];
String[] mark = new String[10];
String evenOrOdd = "";
String output = "";
JTextArea textArea = new JTextArea(12,30);
for(int i = 0; i < number.length; i++) {
number[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
if (number[i] % 2 == 0) {
evenOrOdd = "even";
}
else {
evenOrOdd = "odd ";
}
mark[i] = "";
for(int j = 0; j < number[i]; j++) {
mark[i] = mark[i] + "*";
}
output = output + number[i] + "\t";
output = output + evenOrOdd + "\t";
output = output + mark[i] + "\n";
}
textArea.setText("numbers\ttype\tgraph\n" + output);
JOptionPane.showMessageDialog(null,
textArea,
"OUTPUT",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
The code is missing the bubble sorting and I don't where to put it. Can someone please help me? It doesn't need the user to input anything,
The way you support ascending and descending is to pass a
Comparator
to yoursort()
method and use it to test the results of element comparisons like,Ascending is the default behavor for
Comparable
likeInteger
. So we can delegate tocompareTo()
like,Then descending is the reverse of ascending, so delegate and reverse like
Then test it
Output is