簡體   English   中英

運行代碼時,當第二個數組應按升序或降序排序時,排序方法會打印相同的確切數組編號

[英]When running code, sorting method prints same exact array numbers when the second array should be sorted in ascending or descending order

下面的代碼在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

輸出

您的 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM