簡體   English   中英

Java中的排序算法問題; 得到錯誤的結果

[英]sorting algorithm problem in Java; get wrong results

MainProgram類中創建一個名為indexOfSmallestFrom的類方法。 它的工作方式與上一節中的方法類似,但只考慮來自某個索引的表值。 除了表之外,它還接收這個起始索引作為參數。

在本例中,第一個方法調用從索引 0 開始搜索最小數字的索引。從索引 0 開始,最小數字為 -1,其索引為 0。第二個方法調用搜索最小值的索引從索引 1 開始。在這種情況下,最小的數字是 6,它的索引是 1。第三次調用搜索從索引 2 開始的最小值的索引。那么最小的數字是 8,它的索引是 3。

應該為最小數組打印索引。 根據 int 數組,我的輸出應該是:

1
1
4

但我得到:

1
1
3

無法從邏輯上弄清楚,為什么。

public class MainProgram {

    public static void main(String[] args) {

        int[] array = {3, 1, 5, 99, 3, 12};
        
        System.out.println(MainProgram.indexOfSmallestFrom(array, 0));
        System.out.println(MainProgram.indexOfSmallestFrom(array, 1));
        System.out.println(MainProgram.indexOfSmallestFrom(array, 2));
    }
    
    public static int indexOfSmallestFrom(int[] table, int startIndex){
        int count = startIndex;
        int indexOf = 0;
        int smallest = table[startIndex];
        for(int i = startIndex; i < table.length; i++){
            if(smallest > table[i]){
               smallest = table[i];
               count++;
            }
              indexOf = count; 
        }
            return indexOf;
    }   
 
}

當您發現一個元素小於最初初始化為 startIndex 的 indexOf 處的值時,只需更新 indexOf。

在遍歷所有值之后……返回最終更新的 indexOf。

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {

        int[] array = {3, 1, 5, 99, 3, 12};

        System.out.println(indexOfSmallestFrom(array, 0));
        System.out.println(indexOfSmallestFrom(array, 1));
        System.out.println(indexOfSmallestFrom(array, 2));
    }

    public static int indexOfSmallestFrom(int[] table, int startIndex){
        int indexOf = startIndex;
        int smallest = table[startIndex];
        for(int i = startIndex; i < table.length; i++){
            if(smallest > table[i]){
               smallest = table[i];
               indexOf = i;
            }
        }
            return indexOf;
    }   
}

暫無
暫無

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

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