有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在运行代码时,排序方法会在第二个数组应该按升序或降序排序时打印相同的精确数组号

下面的代码在selectionSorting方法中,这只是一种特定的排序方式。我认为问题出在这里的某个地方,但我不知道如何解决它

if(orderAscending.isSelected()) {
    boolean sorted = false;
    int counting = arrayInt.length-1;
    int errorCounter = 1;
    int tempNum;
    while(sorted == false) {
        if(errorCounter == 0) {
            sorted = true;
        }else {
            errorCounter = 0;
        }
        if(arrayInt[counting] < arrayInt[counting - 1] && sorted != true) {
            tempNum = arrayInt[counting];
            arrayInt[counting] = arrayInt[counting - 1];
            arrayInt[counting - 1] = tempNum;
            errorCounter++;
            counting--;
        }
        if (counting == 0) {
            counting  = arrayInt.length-1;
        }
    }
    String sOutput = "";
    for(int i = 0; i < arrayInt.length-1; i++) {
        sOutput = sOutput + arrayInt[i] + "\n";
    }
    sortedOutput.setText(sOutput);

输出

output


共 (1) 个答案

  1. # 1 楼答案

    while循环应该只包含以下代码

    if(orderAscending.isSelected()) {
                boolean sorted = false;
                int counting = arrayInt.length-1;
                int errorCounter = 1;
                int tempNum,secondLoop;
                while(counting>0) {
                    
                   secondLoop=0;
                 while(secondLoop<=counting){
                    if(arrayInt[counting] < arrayInt[secondLoop]) {
                        tempNum = arrayInt[counting];
                        arrayInt[counting] = arrayInt[secondLoop];
                        arrayInt[secondLoop] = tempNum;
                    }
                  secondLoop++;
                 }
                        counting ;
                }
                String sOutput = "";
                for(int i = 0; i < arrayInt.length-1; i++) {
                    sOutput = sOutput + arrayInt[i] + "\n";
                }
                sortedOutput.setText(sOutput);