gpt4 book ai didi

java - 按升序对数组进行排序

转载 作者:行者123 更新时间:2023-11-30 06:13:54 26 4
gpt4 key购买 nike

所以我现在有这段代码。它运行,但它不会按升序对数字数组进行排序,我不知道我应该怎么做。我是 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);
}
}
}

最佳答案

您似乎在尝试进行冒泡排序,但您的逻辑有点不对劲。将双 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;
}
}
}

关于java - 按升序对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31197521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com