如何显示新排序的整数?

时间:2014-04-24 22:44:41

标签: java sorting

我正在做一个用户输入数字x的项目,然后它将生成x个随机数并将它们添加到arraylist中。在一个文本字段中,它将显示数组中的许多随机整数,然后我必须在另一个文本字段中进行,它通过选择排序对这些数字进行排序。我很确定我的代码是正确的,我只是不确定如何在文本字段#2上显示已排序的数字。继承人我所拥有的:

ArrayList <Integer> Numbers = new ArrayList <Integer>();

....

String input;
int int1,int2 = 0, min = -1000, max = 1000,j, maximum;
input = Input.getText();
int1 = Integer.parseInt(input);


Random number = new Random();

    while(int2 < int1){
for (int i = 0; i < int1; i++){  
    int randomInt = number.nextInt(max - min + 1) + min;
    Numbers.add(randomInt);
     int1--;
}
    }
if(Selection.isSelected() && Ascending.isSelected()){
    for (int i = 0; i<Numbers.size()-1; i++){
        maximum = i;
        for(j = i+1; j<=Numbers.size()-1;j++){
            if(j < i){
                int temp = i;
                i = j;
                j = temp;
            }
        }
    }
}

     Output1.setText("Unsorted Numbers " + Numbers);
     Output2.setText("Sorted Numbers " + //what here? );
     Numbers.clear();

感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

这是怎么回事?

public static void main(String[] args) {

    //min and max value
    int min = -1000;
    int max = 1000;

    //collection to store numbers
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    Random random = new Random();

    //receive input
    Scanner myScanner = new Scanner(System.in);
    int numberFromUser = Integer.parseInt(myScanner.nextLine());
    for (int i = 0; i < numberFromUser; i++) {
        numbers.add(random.nextInt(max - min + 1) + min);
    }

    System.out.println("Unsorted :" + numbers);

    // sort the numbers
    Collections.sort(numbers);
    System.out.println("Sorted   :" + numbers);

    numbers.clear();
}

答案 1 :(得分:0)

你应该准备一个字符串:

String sortedNumbersOutput = "";
for (int i = 0; i < sortedNumbers.size(); i++) {
    sortedNumbersOutput += sortedNumbers.get(i) + (i != sortedNumbers.size() - 1 ? "," : "");
}
Output2.setText("Sorted Numbers " + sortedNumbersOutput );

另外,我不相信你正在整理你的名单......

您正在比较指数而不是这些指数的值。

也许你想尝试一下:

boolean changes = true;
int temp;
while (changes) {
    changes = false;
    for (int i = 0; i < Numbers.size()-1; i++){
        if (Numbers.get(i) > Numbers.get(i+1)) {
            temp = Numbers.get(i);
            Numbers.set(i, Numbers.get(i+1));
            Numbers.set(i+1, temp);
            changes = true;
        }
    }
}

称为bubble sort