So I have this code right now. It runs, but it won't sort the array of numbers in ascending order and I don't know what I should do. I'm new to java so...
import javax.swing.JOptionPane;
public class ThirdClass
{
public static void main (String args[]){
int a = 0;
int b;
int numbers;
int length = Integer.parseInt(JOptionPane.showInputDialog (null, "Input set size", JOptionPane.QUESTION_MESSAGE));
int ctr = 1;
int num[] = new int[length];
for(int i = 0; i < length; i++){
num[i] = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number " + ctr, JOptionPane.QUESTION_MESSAGE));
ctr++;
}
for(int i = 0; i < length; i++){
for(int j = i+1; j < length; j++){
if(num[i]<num[j]){
a = num[i];
num[i] = num[j];
num[j] = a;
}
}
}
for(int i = 0; i < length; i++){
JOptionPane.showMessageDialog (null, "Output: " + num[i] , "Value", JOptionPane.INFORMATION_MESSAGE);
}
}
}
You appear to be trying to do a bubble sort, but your logic is a bit off. Change your double for
loop to this:
for (int i=0; i < length; ++i) {
for (int j=1; j < (length-i); ++j) {
if (num[j-1] > num[j]){
a = num[j-1];
num[j-1] = num[j];
num[j] = a;
}
}
}