[英]Sorting an array in ascending order
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... 我是Java的新手,所以...
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: 将您的double for
循环更改为此:
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;
}
}
}
You don't need to change your complete logic. 您无需更改完整的逻辑。 Just need to change sign less than to greater than Check below code. 只需将符号更改为小于或大于以下代码即可。
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.